Understanding Structures in C#

A structure in C# is simply a composite data type consisting of a number elements of other types. A C# structure is a value type and the instances or objects of a structure are created in stack. The structure in C# can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types. 

Structure Declaration & Object Creation

The keyword struct can be used to declare a structure. The general form of a structure declaration in C# is as follows.         

  1. <modifiers> struct  
  2.     <struct_name> { //Structure members }   

Where the modifier can be private, public, internal or public. The struct is the required keyword.

For example  

  1. struct MyStruct {  
  2.     public int x;  
  3.     public int y;  
  4. }   

The objects of a strcut can be created by using the new operator as follows.    

  1. MyStruct ms = new MyStruct();   

The individual members of a struct can be accessed by using the dot (.) operator as showing below.

  1. ms.x = 10;  
  2. ms.y = 20;   

Remember that unlike classes, the strcut object can also be created without using the new operator.    

MyStruct ms;

But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields are initialized. 

Structs & Fields 

A struct in C# can contain fields. These fields can be declared as private, public, internal. Remember that inside a struct, we can only declare a field. We can't initialize a field inside a struct. However we can use constructor to initialize the structure fields. 

The following is not a valid C# struct and the code will not compile, since the fields inside the structure are trying to initialize.           

  1. struct MyStruct {  
  2.     int x = 20; // Error its not possible to initialize  
  3.     int y = 20; // Error its not possible to initialize  
  4. }   

A valid C# structure is showing below. 

  1. // Author: [email protected]  
  2. using System;  
  3. struct MyStruct {  
  4.     public int x;  
  5.     public int y;  
  6. }  
  7. class MyClient {  
  8.     public static void Main() {  
  9.         MyStruct ms = new MyStruct();  
  10.         ms.x = 10;  
  11.         ms.y = 20;  
  12.         int sum = ms.x + ms.y;  
  13.         Console.WriteLine("The sum is {0}", sum);  
  14.     }  
  15. }   

However a struct can contain static fields, which can be initialized inside the struct. The following example shows the use of static fields inside a struct. 

  1. // Author: [email protected]   
  2. using System;  
  3. struct MyStruct {  
  4.     public static int x = 25;  
  5.     public static int y = 50;  
  6. }  
  7. class MyClient {  
  8.     public static void Main() {  
  9.         int sum = MyStruct.x + MyStruct.y;  
  10.         Console.WriteLine("The sum is {0}", sum);  
  11.     }  
  12. }   
Remember that static fields can't be accessed by an instance of a struct. We can access them only by using the struct names.  

Struct & Methods 

A C# struct can also contain methods. The methods can be either static or non-static. But static methods can access only other static members and they can't invoke by using an object of the structure. They can invoke only by using the struct name.

An example is shown below. 

  1. // Author: [email protected]   
  2. using System;  
  3. struct MyStruct {  
  4.     static int x = 25;  
  5.     static int y = 50;  
  6.     public void SetXY(int i, int j) {  
  7.         x = i;  
  8.         y = j;  
  9.     }  
  10.     public static void ShowSum() {  
  11.         int sum = x + y;  
  12.         Console.WriteLine("The sum is {0}", sum);  
  13.     }  
  14. }  
  15. class MyClient {  
  16.     public static void Main() {  
  17.         MyStruct ms = new MyStruct();  
  18.         ms.SetXY(100, 200);  
  19.         MyStruct.ShowSum();  
  20.     }  
  21. }    
The methods inside a struct can also be overloaded as like inside a class. For example  

  1. // Author:[email protected]    
  2. using System;  
  3. struct MyStruct {  
  4.     static int x = 25;  
  5.     static int y = 50;  
  6.     public void SetXY(int i, int j) {  
  7.         x = i;  
  8.         y = j;  
  9.     }  
  10.     public void SetXY(int i) {  
  11.         x = i;  
  12.         y = i;  
  13.     }  
  14. }  
  15. class MyClient {  
  16.     public static void Main() {  
  17.         MyStruct ms1 = new MyStruct();  
  18.         MyStruct ms2 = new MyStruct();  
  19.         ms1.SetXY(100, 200);  
  20.         ms2.SetXY(500);  
  21.     }  
  22. }  
Structs & Constructors

A C# struct can declare constrcutor, but they must take parameters. A default constructor (constructor without any parameters) are always provided to initialize the struct fields to their default values. The parameterized constructors inside a struct can also be overloaded.   

 

 

  1. // Author: [email protected]   
  2. using System;  
  3. struct MyStruct {  
  4.     int x;  
  5.     int y; {  
  6.         x = i;  
  7.         y = j;  
  8.     }  
  9.     public MyStruct(int i) {  
  10.         x = y = i;  
  11.     }  
  12.     public void ShowXY() {  
  13.         Console.WriteLine("The field values are {0} & {1}", x, y);  
  14.     }  
  15. }  
  16. class MyClient {  
  17.     public static void Main() {  
  18.         MyStruct ms1 = new MyStruct(10, 20);  
  19.         MyStruct ms2 = new MyStruct(30);  
  20.         ms1.ShowXY();  
  21.         ms2.ShowXY();  
  22.     }  
  23. }   
The 'this' operator can also be used in constructors and parameterized constructors can be chained inside a C# constructor. An example is given below.  
  1. // Author: [email protected]  
  2. using System;  
  3. struct MyStruct {  
  4.     int x;  
  5.     int y;  
  6.     public MyStruct(int i, int j): this(i + j) {}  
  7.     public MyStruct(int i) {  
  8.         x = y = i;  
  9.     }  
  10.     public void ShowXY() {  
  11.         Console.WriteLine("The field values are {0} & {1}", x, y);  
  12.     }  
  13. }  
  14. class MyClient {  
  15.     public static void Main() {  
  16.         MyStruct ms1 = new MyStruct(10, 20);  
  17.         ms1.ShowXY();  
  18.     }  
  19. }  
Finally remember that C# struct do not support destructors.  

Structs & Properties 

The properties can be declared inside a struct as shown below.         

  1. //C#: Property  
  2. // Author: [email protected]  
  3. using System;  
  4. class MyStruct  
  5. private int x;  
  6. public int X {  
  7.     get {  
  8.         return x;  
  9.     }  
  10.     set {  
  11.         x = value;  
  12.     }  
  13. }  
  14. }  
  15. class MyClient  
  16. public static void Main() {  
  17.     MyStruct ms = new MyStruct();  
  18.     ms.X = 10;  
  19.     int xVal = ms.X;  
  20.     Console.WriteLine(xVal); //Displays 10   
  21. }  
  22. }  
Structs & Indexers 

The indexers can also be used with a C# struct. An example is shown below.          

  1. // Author: [email protected]   
  2. using System;  
  3. using System.Collections;  
  4. struct MyStruct {  
  5.     public string[] data;  
  6.     public string this[int index] {  
  7.         get {  
  8.             return data[index];  
  9.         }  
  10.         set {  
  11.             data[index] = value;  
  12.         }  
  13.     }  
  14. }  
  15. class MyClient {  
  16.     public static void Main() {  
  17.         MyStruct ms = new MyStruct();  
  18.         ms.data = new string[5];  
  19.         ms[0] = "Rajesh";  
  20.         ms[1] = "A3-126";  
  21.         ms[2] = "Snehadara";  
  22.         ms[3] = "Irla";  
  23.         ms[4] = "Mumbai";  
  24.         Console.WriteLine("{0},{1},{2},{3},{4}", ms[0], ms[1], ms[2], ms[3], ms[4]);  
  25.     }  
  26. }  
Structs & Operator Overloading 

The operators can be overloaded inside a C# structure also. The same rules applicable with respect to a C# class is also applicable here. Both unary and binary operators can be overloaded.          

  1. // Author: [email protected]   
  2. using System;  
  3. struct Complex {  
  4.     private int x;  
  5.     private int y;  
  6.     public Complex(int i, int j) {  
  7.         x = i;  
  8.         y = j;  
  9.     }  
  10.     public void ShowXY() {  
  11.         Console.WriteLine("{0} {1}", x, y);  
  12.     }  
  13.     public static Complex operator - (Complex c) {  
  14.         Complex temp = new Complex();  
  15.         temp.x = -c.x;  
  16.         temp.y = -c.y;  
  17.         return temp;  
  18.     }  
  19. }  
  20. class MyClient {  
  21.     public static void Main() {  
  22.         Complex c1 = new Complex(10, 20);  
  23.         c1.ShowXY(); // displays 10 & 20  
  24.         Complex c2 = new Complex();  
  25.         c2.ShowXY(); // displays 0 & 0  
  26.         c2 = -c1;  
  27.         c2.ShowXY(); // diapls -10 & -20  
  28.     }  
  29. }  
Structs & Inheritance 

There is no inheritance for structs as there is for classes. A struct can't inherit from another struct or class and it can't be the base class for a class. But remember that in C# all types are directly or indirectly inheriting from the super base class object and hence the structure also. Since structs doesn't support inheritance, we can't use the keywords virtual, override, new, abstract etc with a struct methods. C# struct types are never abstract and are always implicitly sealed. The abstract or sealed modifiers are not permitted in a struct declaration. 

Since inheritance is not supported for structs, the declared accessibility of a struct member can't be protected or protected internal. Since all struct types are implicitly inherit from object class, it is possible to override the methods of the object class inside a struct by using the keyword override. Remember that this is special case in C# structs. 

Structs & Interfaces 

Just like classes, a C# struct can also implement from an interface. For example         

  1. // Author:[email protected]    
  2. using System;  
  3. interface IInterface {  
  4.     void Method();  
  5. }  
  6. struct Complex: IInterface {  
  7.     public void Method() {  
  8.         Console.WriteLine("Struct Method");  
  9.     }  
  10. }  
  11. class MyClient {  
  12.     public static void Main() {  
  13.         Complex c1 = new Complex();  
  14.         c1.Method();  
  15.     }  
  16. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  17. if ('this_is' == /an_example/) {  
  18.     of_beautifier();  
  19. else {  
  20.     var a = b ? (c % d) : e[f];  
  21. }  
Structs & Classes 

The structs in C# seems to similar to classes. But they are two entirely different aspects of the language. The classes are reference types while a struct is a value type in C#. The objects of class types are always created on heal while the objects of struct types are always created on the stack. But C# structs are useful for small data structures that have value semantics. Complex numbers, points in a co-ordinate systems etc are good examples for struct types.

Up Next
    Ebook Download
    View all
    Learn
    View all