What Is Struct And When To Use Struct In C#

In this article, I am going to share information with you about Structures in C#.
 
What is Structure?
 
Follow the steps to learn what Structure really is:
 
'Struct' keyword is used to create a structure. A structure can contain variables, methods, static constructor, parameterized constructor, operators, indexers, events, and property.
 
The syntax of Structure,
  1. struct Struct_Name  
  2. {  
  3.     //Structure members  
  4. }  
We have use variables, methods, and property inside the structure as shown in the below program. Struct members can be static and non-static.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         struct Student  
  8.         {  
  9.             //Variables  
  10.             int Roll_no;  
  11.             string Name;  
  12.             string Mobile;  
  13.   
  14.             //Enum  
  15.             enum course { BTech, MBA, BPharma, MA, BSc }  
  16.   
  17.             // Static method  
  18.             public static void marks()  
  19.             {  
  20.                 Console.WriteLine("Marks");  
  21.             }  
  22.   
  23.             // Method  
  24.             public void Grades()  
  25.             {  
  26.                 Console.WriteLine("Grades");  
  27.             }  
  28.   
  29.             //Property  
  30.             public int Serial_No { getset; }  
  31.   
  32.         }  
  33.   
  34.         static void Main(string[] args)  
  35.         {  
  36.             Console.ReadKey();  
  37.         }  
  38.     }  
  39. }  
A structure can not derive/inherit from any structure or class.
 
As shown in the below program when a struct 'Syllabus' tries to inherit/derive a struct 'Student' then the compiler will produce an error as "Type 'Program.Student' in interface list is not an interface". The same error will be produced if struct tries to inherit/derive a class.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         struct Student  
  8.         {  
  9.             //Variables  
  10.             int Roll_no;  
  11.             string Name;  
  12.             string Mobile;  
  13.   
  14.             //Enum  
  15.             enum course { BTech, MBA, BPharma, MA, BSc }  
  16.   
  17.             // Static method  
  18.             public static void marks()  
  19.             {  
  20.                 Console.WriteLine("Marks");  
  21.             }  
  22.   
  23.             // Method  
  24.             public void Grades()  
  25.             {  
  26.                 Console.WriteLine("Grades");  
  27.             }  
  28.   
  29.             //Property  
  30.             public int Serial_No { getset; }  
  31.   
  32.         }  
  33.   
  34.         // When Struct 'Syllabus' try to inherit from Struct 'Student' then compiler will produce an error  
  35.         // Error as "Type 'Program.Student' in interface list is not an interface"  
  36.         struct Syllabus : Student  
  37.         {  
  38.             int Roll_no;  
  39.             int status;  
  40.         }  
  41.   
  42.         static void Main(string[] args)  
  43.         {  
  44.             Console.WriteLine("December ");  
  45.             Console.ReadKey();  
  46.         }  
  47.     }  
  48. }  
A Structure can implement any number of interfaces
 
In the below program, struct 'Student' implemented 2 interfaces 'IStudent' and 'IRecords'. Method of Interface 'IRecords' is defined inside the struct.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         interface IStudent  
  8.         {  
  9.         }  
  10.         interface IRecords  
  11.         {  
  12.             void Records();  
  13.         }  
  14.         //struct implements 2 interfaces 'IRecords' and 'IStudent'  
  15.         struct Student : IStudent, IRecords  
  16.         {  
  17.             public int Roll_no;  
  18.             public string Name;  
  19.             public string Mobile;  
  20.             //Method from IRecords interface is defined  
  21.             public void Records()  
  22.             {  
  23.                 Console.WriteLine("Records");  
  24.             }  
  25.   
  26.         }  
  27.         static void Main(string[] args)  
  28.         {  
  29.             //struct object is creating  
  30.             Student student = new Student();  
  31.             student.Records();  
  32.             Console.ReadKey();  
  33.         }  
  34.     }  
  35. }  
Output
  1. Records  
Constructor
 
We cannot define default constructor in structure. If we try to define then the compiler will produce an error as "Structs cannot contain explicit parameterless constructor". We can define static constructor and parameterised constructor. Have a look at the below program to understand more. If we notice the output of this program then 'Static Constructor' is written on the first line. Why so? A static constructor is called automatically while initializing the struct when an instance is created.

In the Main method, first, we create an object of struct 'Student' as we did for class. In next line, we get the values of struct members with struct object followed by (.) and struct member name.
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         struct Student  
  8.         {  
  9.             //Variables  
  10.             public int Roll_no;  
  11.             public string Name;  
  12.             public string Mobile;  
  13.   
  14.             //Enum  
  15.             public enum course { BTech, MBA, BPharma, MA, BSc }  
  16.   
  17.             // Static Constructor, valid  
  18.             static Student()  
  19.             {  
  20.                 Console.WriteLine("Static Constructor");  
  21.             }  
  22.   
  23.             // Struct does not contain Default Constructor  
  24.             // It will produce an error as "Structs cannot contain explicit parameterless constructor"  
  25.             public Student()  
  26.             {  
  27.                 Console.WriteLine("Default Constructor");  
  28.             }  
  29.   
  30.             // Parameterised Constructor  
  31.             // Valid, This constructor should return all the values of the struct members and must contain all the arguments  
  32.             public Student(int roll, string name, string mobile, int serial)  
  33.             {  
  34.                 Roll_no = roll;  
  35.                 Name = name;  
  36.                 Mobile = mobile;  
  37.                 Serial_No = serial;  
  38.             }  
  39.   
  40.             //Property  
  41.             public int Serial_No { getset; }  
  42.   
  43.         }  
  44.   
  45.   
  46.         static void Main(string[] args)  
  47.         {  
  48.             // Creating object of struct 'Student' by passing parametres to it  
  49.             Student student = new Student(3, "Shubham""9821705378", 1);  
  50.             //Struct value are get with struct object followed by (.) and struct member name  
  51.             Console.WriteLine("Roll no: " + student.Roll_no + " Name: " + student.Name + " Mobile no: " + student.Mobile + " Serial no: " + student.Serial_No);  
  52.             Console.ReadKey();  
  53.         }  
  54.     }  
  55. }  
Output
  1. Static Constructor  
  2. Roll no: 3 Name: Shubham Mobile no: 9821705378 Serial no: 1  
Destructor
 
A struct cannot contain destructor. It will produce the compiler error as "Only class types can contain destructors" as shown in below example
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         struct Student  
  8.         {  
  9.             //Variables  
  10.             public int Roll_no;  
  11.             public string Name;  
  12.             public string Mobile;  
  13.   
  14.   
  15.             // Destructor  
  16.             // Struct cannot contain destructors. It will produce a compile error as "Only class types can contain destructors"  
  17.             ~Student()  
  18.             {  
  19.                 Console.WriteLine("Destructor");  
  20.             }  
  21.   
  22.         }  
  23.         static void Main(string[] args)  
  24.         {  
  25.             Console.ReadKey();  
  26.         }  
  27.     }  
  28. }  
Cannot initialize struct member inside struct
 
In a struct, we cannot initialize struct member with a value. This will produce a compile error as "Program.Student cannot have instance property or field initializers in structs"
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         struct Student  
  8.         {  
  9.             //Variables 'Roll_no', 'Name' and 'Mobile' are initialised with value which is not possible in struct.  
  10.             //It will produce a compile error as "Program.Student cannot have instance property or field initializers in structs"  
  11.             public int Roll_no = 11;  
  12.             public string Name = "Shubham";  
  13.             public string Mobile = "9821705378";  
  14.   
  15.         }  
  16.         static void Main(string[] args)  
  17.         {  
  18.             Console.ReadKey();  
  19.         }  
  20.     }  
  21. }  
When to use Structures? Is There a Difference between Class and Structure?
 
Well, there is a lot of discussion on whether we use class or structure. There are already a lot of answers to this question and the best ones are below. I have taken reference from this link.When to use structure in c#
 
1) Structures provide better performance when we have small collections of value-types that you want to group together.
 
2) Use Structure if all member fields are of value type. Use Class if any one member is of reference type.
 
3) In C#, using a value type instead of a reference type will result in fewer objects on the managed heap, which results in a lesser load on the garbage collector (GC), less frequent GC cycles, and consequently better performance. However, value types have their downsides too. Passing around a big struct is definitely costlier than passing a reference, that's one obvious problem.
 
4) A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data. A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable, therefore, contain two separate copies of the same data. Changes made to one copy do not affect the other copy. In general, classes are used to model more complex behavior or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
 
5) A struct is a value type. If you assign a struct to a new variable, the new variable will contain a copy of the original.
  1. public struct IntStruct  
  2. {  
  3.     public int Value { getset; }  
  4. }  
Execution of the following results in 5 instances of the struct stored in memory:
  1. var struct1 = new IntStruct() { Value = 0 }; // original  
  2. var struct2 = struct1; // A copy is made  
  3. var struct3 = struct2; // A copy is made  
  4. var struct4 = struct3; // A copy is made  
  5. var struct5 = struct4; // A copy is made  
  6.   
  7. // NOTE: A "copy" will occur when you pass a struct into a method parameter.  
  8. // To avoid the "copy", use the ref keyword.  
  9.   
  10. // Although structs are designed to use less system resources  
  11. // than classes. If used incorrectly, they could use significantly more.  
A class is a reference type. When you assign a class to a new variable, the variable contains a reference to the original class object.
  1. public class IntClass  
  2. {  
  3.     public int Value { getset; }  
  4. }  
Execution of the following results in only one instance of the class object in memory.
  1. var class1 = new IntClass() { Value = 0 };  
  2. var class2 = class1; // A reference is made to class1  
  3. var class3 = class2; // A reference is made to class1  
  4. var class4 = class3; // A reference is made to class1  
  5. var class5 = class4; // A reference is made to class1  
Structs may increase the likelihood of a code mistake. If a value object is treated like a mutable reference object, a developer may be surprised when changes made are unexpectedly lost.
  1. var struct1 = new IntStruct() { Value = 0 };  
  2. var struct2 = struct1;  
  3. struct2.Value = 1;  
  4. // At this point, a developer may be surprised when  
  5. // struct1.Value is 0 and not 1  
Reference

https://stackoverflow.com/questions/521298/when-to-use-struct
 
Conclusion
 
Structures provide better performance as it is value type. Using a value type will result in fewer objects on the managed heap, which results in lesser load on the garbage collector (GC), less frequent GC cycles, and consequently better performance. However, value types have their downsides too. Passing around a big struct is definitely costlier than passing a reference, that's one obvious problem. I hope this article helps you to understand a bit more about struct.
 
Thank you and  feel free to ask any question or make a suggestion.

Up Next
    Ebook Download
    View all
    Learn
    View all