Sign in to follow this  
Calin

[.net] Copying an object to another [solved]

Recommended Posts

Calin    419
class Something
{
private List <string> Strings;
public void clear()
{
Strings.Clear();
}
}

Something A;
Something B;

A = B;
A.Clear();



Will A.Clear() make the B.Strings empty too? It shouldn't in my opinion. However this is what takes place in my code. If I call A.Clear() ,B.Strings gets emptied, otherwise it stays intact. [Edited by - Calin on April 24, 2006 1:25:12 PM]

Share this post


Link to post
Share on other sites
zangetsu    272
Thats what .Clone is for. To use it your object needs to implement IClonable. I'd be more specific, but I'm a VB.Net guy and you're clearly not.

Share this post


Link to post
Share on other sites
Machaira    1033
Quote:
Original post by Calin
*** Source Snippet Removed ***
Will A.Clear() make the B.Strings empty too? It shouldn't in my opinion.

Why shouldn't it? You're not copying B to A, you're making A a reference to B. Unfortunately you can't overload the = operator in C#. You could create a Copy method though:


class Something
{
private List<string> Strings;

public void clear()
{
Strings.Clear();
}

public string GetStringItem(int index)
{
return Strings[index];
}

public void SetStringItem(int index, string data)
{
Strings[index] = data;
}

public Something Copy(Something obj)
{
for(int i=0;i<Strings.Count;i++)
obj.SetStringItem(i,Strings[i]);
}


Share this post


Link to post
Share on other sites
Calin    419
Thanks!

I knew you can't use pointers in C# so I thought the refereces don't work either.

Making a Clone function made it. I'll take a look into IClonable too. I'm still newbie to C#.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this