Tuesday, April 29, 2008

Classes vs Structures

Ever wondered what are the differences between classes and structures and when you should use which one. According to Donis Marshall in his book called Visual C# 2005: The Language he mentions:

"Structures are lightweight classes. Because structures reside on the stack, keep them small. Do not cache large objects on the stack. The implementation of structures in C# enforces the policy of using a structure as lightweight class. The following list details the differences between structures and classes:

  • Structures are sealed and cannot be inherited.
  • Structures cannot inherit classes and other structures
  • Structure implicitly inherits from System.ValueType
  • The default constructor of a structure cannot be replaced by a custom constructor.
  • Structures do not have destructors.
  • Field initialization is not allowed. Const members of a structure can be initialized. "

No comments: