Structures in C#

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. {  
  4.     // Fields  
  5.     private string Empname;  
  6.     private int Empid;  
  7.     // Property  
  8.     public string Empname  
  9.     {  
  10.         get  
  11.         {  
  12.             return Empname;  
  13.         }  
  14.         set  
  15.         {  
  16.             Empname = value;  
  17.         }  
  18.     }  
  19.     // Method  
  20.     public int GetEmpid()  
  21.     {  
  22.         return Empid;  
  23.     }  
  24. }  

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.


Recommended Free Ebook
Similar Articles