Sign in to follow this  
Calin

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

Recommended Posts

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
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
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