To use a struct, we need to instantiate the struct and use it just like a class. Then why don\'t we just create a class in the first place?
A major difference between the semantics of class
and struct
is that struct
s have value semantics. What is this means is that if you have two variables of the same type, they each have their own copy of the data. Thus if a variable of a given value type is set equal to another (of the same type), operations on one will not affect the other (that is, assignment of value types creates a copy). This is in sharp contrast to reference types.
There are other differences:
sealed
(it is not possible to derive from a value type).null
.A
could refer to a instance of type B
if B
derives from A
.Because of the difference in semantics, it is inappropriate to refer to struct
s as "lightweight classes."