Sunday, September 14, 2008

C# : Value Types

VT == ValueTypes
RT == ReferenceTypes

VT are simple types - they do not carry storage overheads -->this reduces the cost of creating a object since VT do not have object header, method invocation against a VT does not use virtual method dispatch - this helps performance but loses some flexibility.
VT dont have sync block index, so multiple threads cannot synchronize their access over a VT
VT have System.ValueType as base type.
VT are - structs,enum,bool,int family,etc
VT are marked as sealed and cannot be used as base type.
VT are allocated on stack and not heap,
VT cannot have finalizers
VT cannot have default constructors
VT can be boxed or unboxed, RT are always boxed
VT variables always contain a value of the underlying type - VT variable is never null
when you assign a VT to another, a field by field copy is made.
VT have a different .Equals and .GetHashCode method from RT.(overloaded by System.ValueType)

Defining custom VT - using enum or structs constructs

struct types -
cannot have explicit base class it is always System.ValueType
cannot declare struct as abstract or sealed, compiler implicitly adds sealed - cannot inherit from structs
has LayoutKind.Sequential attribute

When to declare types are VT
1. When the type is simple, that has no members that modify any of the type's instancec feilds, when a type offers no members that alter its fields, we say the type is immutable
2. The type doesn't need to inherit from any other type
3. the type wont have any other types derived from it.
4. Instances of the type are small (16 bytes or less)
5. Instances of the type are large(>16bytes) and are not passed as method parameters or returned from methods.

No comments: