Struct
and Class
value type
and reference type
In my study, I had learned the struct
from the C language. I understood this as the group of variable. Now, with my knowledge, the struct
is kind of value type group which means each instance act as they are original. This feature can be seen at the copy. Similar with the integer, char or other types, the struct can copy without the modification. Following code snippet shows the characteristic of value type. Copying(linking) it by b=a
command. Increasing the b
after copying a
does not affect to a.
int a = 10; // a:10
int b = a; // a:10, b:10
b++; // a:10, b:11
However, there is other type of variable, reference type. Easily understood the reference type which transfer their information via address. In case of copying, they shows different comparing with value type. The modification of copied object affect on the linked object(origin). The reason of this feature is that the instance share their address with two indicator.
List<int> lis_a = new List(){1,2,3}; // lis_a: {1,2,3}
List<int> lis_b = lis_a; // lis_a: {1,2,3}, lis_b: {1,2,3}
lis_b.Add(4); // lis_a: {1,2,3,4}, lis_b:{1,2,3,4}
So, the many code style contains the deep-copy-method(making new instance which dont affect origin). The second one, generator - deep copy
generate instance based on the data of mediator. However, the generated instance is different with the origin. This would be used for the situation needs each different instance.
public class MyClass
{
int a,b;
// generator - default
public MyClass()
{
a = <initial value>;
b = <initial value>;
}
// generator - deep copy
public MyClass(MyClass my)
{
this.a = my.a;
this.b = my.b;
}
}