Monday, July 6

C# Struct

Struct is a value type.
The first difference between a reference types and value types is that reference types are allocated on the heap and value types are allocated inline or on the stack. The are deallocated when the stack unwinds or when the containing type gets deallocated. Therefore, allocated and deallocated is generally cheaper.

The second difference is related to memory usage. Value types get boxed when cast to a reference type or one of the interfaces they implement. They get unboxed when east back to the value type. Because boxes are objects that are allocated on the heap and are garbage collected. Too much boxing and unboxing can have a negative impact on the heap.

Third, reference types assignments copy the reference, whereas value type assignments copy the entire value.

Fourth, reference types are passed by reference, where as types are passed by value.