Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I have this example:


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

  • *Experts*
Posted

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

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

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

Posted

How about this?

 

static void testfunction(testclass test2) {

testclass test3 = new testclass(test2.i);

test3.i++;

}

 

Otherwise, you really have to implement ICloneable.

Posted

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...