Struct vs Class: By value or reference

public struct Car {
public int Gears;
}
..and..
public class Car {
public int Gears;
}
..looks almost the same. But there's a huge different how they are handled. Structs are always copied as values when assigned to another variable in contrast to classes that copied as a reference to the original object.

If you run the following code:
Car car1 = new Car();
car1.Gears = 4;
Car car1copy = car1;
car1copy.Gears = 5;
..and Car is a struct, then car1.Gears still would be 4 eventhough the copies Gears was changed. If, instead, Car is a class car1copy would be a reference to car1 thus resulting in car1.Gears also becoming 5.

Related posts:

Comments

comments powered by Disqus