Thursday, March 11, 2010

struct and a class

Here are just some of the differences between a struct and a class:

* Classes are reference types and structs are value types. Since classes are reference type, a class variable can be assigned null, but we cannot assign null to a struct variable, since structs are value type.
* You will always be dealing with reference to an object ( instance ) of a class. But you will not be dealing with references to an instance of a struct, you will be dealing directly with struct
* Classes must be instantiated using the new operator, but structs can be instantiated without using the new operator.
* Classes support inheritance.But there is no inheritance for structs, (structs don't support inheritance polymorphism )
* It is not mandatory to initialize all Fields inside the constructor of a class. But all the Fields of a struct must be fully initialized inside the constructor.
* structs object is allocated in the stack, and the class object is allocated in the heap.

Class are usually for large amounts of data, whereas structs are smaller, and often used when you want to group similar data together. Use a class when object identity is more important than value. Use a struct when the value contained by an instance is more important than instance identity.

Struct variables directly contain their values, so when you pass a struct instance as a parameter, it can be more expensive than passing an instance of a reference type, due to
the copying costs.

No comments: