Structures

In C#, a structure is a value type data type. It helps you to make a single variable to hold the related data of various data types. Structures are used to represent a record.

Features of Structures

Structure members cannot be specified as abstract, virtual, or protected.

  • Structures can have methods, fields, indexers, properties, operator methods and events.
  • Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
  • Unlike classes, structures cannot inherit other structures or classes.
  • Structures cannot be used as a base for other structures or classes.
  • A structure can implement one or more interfaces.
  • When you create a struct object using the New operator, it is created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator.
  • If the new operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.
  1. public struct Struct_Emp
  2. {
  3. // Fields
  4. private string Empname;
  5. private int Empid;
  6. // Property
  7. public string Empname
  8. {
  9. get
  10. {
  11. return Empname;
  12. }
  13. set
  14. {
  15. Empname = value;
  16. }
  17. }
  18. // Method
  19. public int GetEmpid()
  20. {
  21. return Empid;
  22. }
  23. }

Class Vs Structures

  • classes are reference types and structs are value types
  • structures do not support inheritance
  • structures cannot have default constructor

When to use Structures

  • When you want your type to look and feel like a primitive type.
  • When you create many instances, use them briefly and then drop them. For for example, within a loop.
  • The instances you create are not passed around a lot.
  • When you don't want to derive from other types or let others derive from your type.
  • When you want others to operate on a copy of your data (basically pass by value semantics).

When not to use Structures

The size of the struct (the sum of the sizes of its members) is large

  • You create instances, put them in a collection, iterate and modify elements in the collection. This will result in many boxing/unboxing since FCL Collections operate on the system.