Monday, July 9, 2007

What is the difference between a Struct and a Class?

  • Structs are value-type variables and are thus saved on the stack, where as classes are of reference type and are stored on heap.
  • Creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a class instance can cause garbage collection.
  • A struct is implicitly sealed, a class isn't.
  • A struct can't be abstract, a class can.
  • A struct can't call : base() in its constructor whereas a class with no explicit base class can.
  • A struct can't extend another class, a class can.
  • A struct can't declare protected members (eg fields, nested types) a class can.
  • A struct can't declare abstract function members, an abstract class can.
  • A struct can't declare virtual function members, a class can.
  • A struct can't declare sealed function members, a class can.
  • A struct can't declare override function members, a class can. The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString().
  • Fields in a struct have to be initialized in a constructor whereas fields in a class can be initialized at their point of declaration.
  • You can't declare a user-defined struct type as a volatile field but you can declare a user-defined class type as a volatile field.
  • A struct type expression cannot be the operand of a lock statement.
  • A struct type cannot be the right hand side operand of the as operator.
  • A struct instance cannot be null.
  • A structs static constructor is not triggered by calling the structs default constructor. It is for a class.
  • A struct always has a built-in public default constructor. This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.

No comments: