xSwan Posted July 6, 2003 Posted July 6, 2003 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 Quote
*Experts* Nerseus Posted July 7, 2003 *Experts* Posted July 7, 2003 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 Quote "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
xSwan Posted July 7, 2003 Author Posted July 7, 2003 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.? Quote
Heiko Posted July 7, 2003 Posted July 7, 2003 Some classes implement .clone methods. For your own classes, you have to implement your own clone method. Quote .nerd
xSwan Posted July 8, 2003 Author Posted July 8, 2003 Yeah, I could add a methods, but isn't there an other way? Quote
JABE Posted July 8, 2003 Posted July 8, 2003 How about this? static void testfunction(testclass test2) { testclass test3 = new testclass(test2.i); test3.i++; } Otherwise, you really have to implement ICloneable. Quote
xSwan Posted July 8, 2003 Author Posted July 8, 2003 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 :( Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.