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,
We have use variables, methods, and property inside the structure as shown in the below program. Struct members can be static and non-static.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- struct Student
- {
-
- int Roll_no;
- string Name;
- string Mobile;
-
-
- enum course { BTech, MBA, BPharma, MA, BSc }
-
-
- public static void marks()
- {
- Console.WriteLine("Marks");
- }
-
-
- public void Grades()
- {
- Console.WriteLine("Grades");
- }
-
-
- public int Serial_No { get; set; }
-
- }
-
- static void Main(string[] args)
- {
- Console.ReadKey();
- }
- }
- }
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.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- struct Student
- {
-
- int Roll_no;
- string Name;
- string Mobile;
-
-
- enum course { BTech, MBA, BPharma, MA, BSc }
-
-
- public static void marks()
- {
- Console.WriteLine("Marks");
- }
-
-
- public void Grades()
- {
- Console.WriteLine("Grades");
- }
-
-
- public int Serial_No { get; set; }
-
- }
-
-
-
- struct Syllabus : Student
- {
- int Roll_no;
- int status;
- }
-
- static void Main(string[] args)
- {
- Console.WriteLine("December ");
- Console.ReadKey();
- }
- }
- }
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.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- interface IStudent
- {
- }
- interface IRecords
- {
- void Records();
- }
-
- struct Student : IStudent, IRecords
- {
- public int Roll_no;
- public string Name;
- public string Mobile;
-
- public void Records()
- {
- Console.WriteLine("Records");
- }
-
- }
- static void Main(string[] args)
- {
-
- Student student = new Student();
- student.Records();
- Console.ReadKey();
- }
- }
- }
Output
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.
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- struct Student
- {
-
- public int Roll_no;
- public string Name;
- public string Mobile;
-
-
- public enum course { BTech, MBA, BPharma, MA, BSc }
-
-
- static Student()
- {
- Console.WriteLine("Static Constructor");
- }
-
-
-
- public Student()
- {
- Console.WriteLine("Default Constructor");
- }
-
-
-
- public Student(int roll, string name, string mobile, int serial)
- {
- Roll_no = roll;
- Name = name;
- Mobile = mobile;
- Serial_No = serial;
- }
-
-
- public int Serial_No { get; set; }
-
- }
-
-
- static void Main(string[] args)
- {
-
- Student student = new Student(3, "Shubham", "9821705378", 1);
-
- Console.WriteLine("Roll no: " + student.Roll_no + " Name: " + student.Name + " Mobile no: " + student.Mobile + " Serial no: " + student.Serial_No);
- Console.ReadKey();
- }
- }
- }
Output
- Static Constructor
- 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
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- struct Student
- {
-
- public int Roll_no;
- public string Name;
- public string Mobile;
-
-
-
-
- ~Student()
- {
- Console.WriteLine("Destructor");
- }
-
- }
- static void Main(string[] args)
- {
- Console.ReadKey();
- }
- }
- }
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"
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- struct Student
- {
-
-
- public int Roll_no = 11;
- public string Name = "Shubham";
- public string Mobile = "9821705378";
-
- }
- static void Main(string[] args)
- {
- Console.ReadKey();
- }
- }
- }
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.
- public struct IntStruct
- {
- public int Value { get; set; }
- }
Execution of the following results in 5 instances of the struct stored in memory:
- var struct1 = new IntStruct() { Value = 0 };
- var struct2 = struct1;
- var struct3 = struct2;
- var struct4 = struct3;
- var struct5 = struct4;
-
-
-
-
-
-
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.
- public class IntClass
- {
- public int Value { get; set; }
- }
Execution of the following results in only one instance of the class object in memory.
- var class1 = new IntClass() { Value = 0 };
- var class2 = class1;
- var class3 = class2;
- var class4 = class3;
- var class5 = class4;
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.
- var struct1 = new IntStruct() { Value = 0 };
- var struct2 = struct1;
- struct2.Value = 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.