Tuesday, August 13, 2013

Class Vs Struct and Boxing unboxing

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object.
In the following example, the integer variable i is boxed and assigned to object o.
int i = 123;
// The following line boxes i. 
object o = i;  
The object o can then be unboxed and assigned to integer variable i:
o = 123;
i = (int)o;  // unboxing
Feature
Struct
Class
Notes
Is a reference type?
No
Yes*

Is a value type?
Yes
No

Can have nested Types (enum, class, struct)?
Yes
Yes

Can have constants?
Yes
Yes

Can have fields?
Yes*
Yes
Struct instance fields cannot be initialized, will automatically initialize to default value.
Can have properties?
Yes
Yes

Can have indexers
Yes
Yes

Can have methods?
Yes
Yes

Can have events?
Yes*
Yes
Structs, like classes, can have events, but care must be taken that you don’t subscribe to a copy of a struct instead of the struct you intended.
Can have static members (constructors, fields, methods, properties, etc.)?
Yes
Yes

Can inherit?
No*
Yes*
Classes can inherit from other classes (or object by default). Structs always inherit fromSystem.ValueType and are sealed implicitly
Can implement interfaces?
Yes
Yes

Can overload constructor?
Yes*
Yes
Struct overload of constructor does not hide default constructor.
Can define default constructor?
No
Yes
The struct default constructor initializes all instance fields to default values and cannot be changed.
Can overload operators?
Yes
Yes

Can be generic?
Yes
Yes

Can be partial?
Yes
Yes

Can be sealed?
Always*
Yes
Structs are always sealed and can never be inherited from.
Can be referenced in instance members using this keyword?
Yes*
Yes
In structs, this is a value variable, in classes, it is a readonly reference.
Needs new operator to create instance?
No*
Yes
C# classes must be instantiated using new. However, structs do not require this. While new can be used on a struct to call a constructor, you can elect not to use new and init the fields yourself, but you must init all fields and the fields must be public!

No comments:

Post a Comment