Click here to Skip to main content
15,906,463 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I created a class in c#:

C#
public myClass()
{
  .....
}


1) If I assign the class like this:

C#
myClass m1 = new myClass();
....
myClass m2 = m1;


will m1 be copied (by value) to m2, or will it be assigned by reference?

2)I created an ArrayList.
If I add an instance of myClass to the ArrayList, will it be added by value (copy) or by reference?

Thanks
Posted
Comments
bbirajdar 18-Oct-12 5:27am    
by ref

If it is class, it will be assigned by ref :)
 
Share this answer
 
Classes are always References (structs are Value types) and References are always copies of the reference, not the values within the class itself unless a copy constructor is created, and used explicitly: http://msdn.microsoft.com/en-us/library/ms173116(v=vs.80).aspx[^]

So an assignment of a reference value to another reference variable will always result in two references that "point" at the same data instance:
C#
MyClass m1 = new MyClass();
m1.Name = "Joe";
MyClass m2 = m1;
Console.WriteLine (m1.Name + " = " + m2.Name);
m1.Name = "Mike";
Console.WriteLine (m1.Name + " = " + m2.Name);

Will output:
Joe = Joe
Mike = Mike
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900