Creat a copy

xSwan

Newcomer
Joined
Jun 15, 2003
Messages
20
Location
Denmark
I have this example:
C#:
class testclass
	{
		public int i;
		public testclass(int i)
		{
		this.i = i;
		}
	}

	class Class1
	{		[STAThread]
		static void Main(string[] args)
		{
			testclass test1 = new testclass(0);
			testfunction(test1);
			Console.Write(test1.i);
			Console.Read();


		}
		static void testfunction(testclass test2)
		{
			testclass test3 = test2;
			test3.i++;
		}
	}

What can i do if i dont want test1 to be 1 then I call the testfunction?

Sorry for the variable but I'm not good for find names for varibles, :D
 
If you're asking why the testfunction, which assigns test3 to test2 also increments the private variable i inside of class2, it's because the contents of a class are not copied even when a function is declared as by val (meaning you did NOT use ref or out).

To have testfunction work on a copy of the test class passed in, you'd have to perform a shallow copy and work with that. You could also define the testclass Class to be a struct. The contents of a struct is passed by value so incrementing a member variable would affect the copy, not the original.

Otherwise, things are working as expected - at least they are to me. It's a matter of realizing what's working so you know what to expect then coding with that knowledge in mind.

-Nerseus
 
Yah, I'm understand what it do then I see it do it, but my question is, how can I copy the test2 into test3 and do what I want to with the test3, without the test1 be chance to?

And I cant just made it to a struct becurse realy its other class, I take from a Direct3.

So my real question is, how can I copy a class and not only its ref.?
 
How about this?

static void testfunction(testclass test2) {
testclass test3 = new testclass(test2.i);
test3.i++;
}

Otherwise, you really have to implement ICloneable.
 
Nope, it can't do it, too :(
Bcurse it, the testclass, just is a test of how it work, not the real object. So I must try to find an other way to sovle my problem :(
 
Back
Top