Classes:
- Can support inheritance
- lives on the heap
- Are reference (pointer) types. Value passing around from method to method
- The reference can be null
- Have memory overhead per new instance
- Can have an explicit parameterless constructor
- Can have destructors
Structs:
- Cannot support inheritance
- lives on the stack
- Are value types
- Are passed by value: all struct types implicitly inherit from the class System.ValueType. Assignment to a variable of a struct type creates a copy of the value being assigned
- Cannot have a null reference (unless Nullable is used)
- Do not have a memory overhead per new instance - unless 'boxed'
- Cannot have an explicit parameterless constructor
- Cannot have destructors
Both Classes and Structs:
- Are compound data types typically used to contain a few variables that have some logical relationship
- Can contain methods and events
- Can support interfaces
When should you use Structs: base on Microsoft MSDN
CONSIDER defining a struct
instead of a class if instances of the type are small and commonly short-lived
or are commonly embedded in other objects.
AVOID defining a struct unless
the type has all of the following characteristics:
·
It logically represents a single value, similar
to primitive types.
·
It has an instance size under 16 bytes.
·
It is immutable.
·
It will not have to be boxed frequently.
0 comments:
Post a Comment