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.

The 'Struct' keyword is used to create a structure. A structure can contain variables, methods, static constructors, parameterized constructors, operators, indexers, events, and properties.

The syntax of Structure,

struct Struct_Name  
{  
    // Structure members  
}

We have used variables, methods, and properties 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
        {
            // Variables
            int Roll_no;
            string Name;
            string Mobile;

            // Enum
            enum course { BTech, MBA, BPharma, MA, BSc }

            // Static method
            public static void marks()
            {
                Console.WriteLine("Marks");
            }

            // Method
            public void Grades()
            {
                Console.WriteLine("Grades");
            }

            // Property
            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 the struct tries to inherit/derive a class.

using System;

namespace Tutpoint
{
    class Program
    {
        struct Student
        {
            // Variables
            int Roll_no;
            string Name;
            string Mobile;

            // Enum
            enum course { BTech, MBA, BPharma, MA, BSc }

            // Static method
            public static void marks()
            {
                Console.WriteLine("Marks");
            }

            // Method
            public void Grades()
            {
                Console.WriteLine("Grades");
            }

            // Property
            public int Serial_No { get; set; }
        }

        // When Struct 'Syllabus' try to inherit from Struct 'Student' then compiler will produce an error
        // Error as "Type 'Program.Student' in interface list is not an interface"
        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 implements 2 interfaces 'IRecords' and 'IStudent'
        struct Student : IStudent, IRecords
        {
            public int Roll_no;
            public string Name;
            public string Mobile;
            //Method from IRecords interface is defined
            public void Records()
            {
                Console.WriteLine("Records");
            }

        }
        static void Main(string[] args)
        {
            //struct object is creating
            Student student = new Student();
            student.Records();
            Console.ReadKey();
        }
    }
}

Output

Records

Constructor

We cannot define the default constructor in the structure. If we try to define then the compiler will produce an error as "Structs cannot contain explicit parameterless constructor". We can define static constructors and parameterized constructors. 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 the 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
        {
            //Variables
            public int Roll_no;
            public string Name;
            public string Mobile;

            //Enum
            public enum course { BTech, MBA, BPharma, MA, BSc }

            // Static Constructor, valid
            static Student()
            {
                Console.WriteLine("Static Constructor");
            }

            // Struct does not contain Default Constructor
            // It will produce an error as "Structs cannot contain explicit parameterless constructor"
            public Student()
            {
                Console.WriteLine("Default Constructor");
            }

            // Parameterised Constructor
            // Valid, This constructor should return all the values of the struct members and must contain all the arguments
            public Student(int roll, string name, string mobile, int serial)
            {
                Roll_no = roll;
                Name = name;
                Mobile = mobile;
                Serial_No = serial;
            }

            //Property
            public int Serial_No { get; set; }
        }

        static void Main(string[] args)
        {
            // Creating object of struct 'Student' by passing parameters to it
            Student student = new Student(3, "Shubham", "9821705378", 1);
            //Struct values are obtained with struct object followed by (.) and struct member name
            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 a destructor. It will produce the compiler error "Only class types can contain destructors" as shown in the below example.

using System;

namespace Tutpoint
{
    class Program
    {
        struct Student
        {
            //Variables
            public int Roll_no;
            public string Name;
            public string Mobile;


            // Destructor
            // Struct cannot contain destructors. It will produce a compile error as "Only class types can contain destructors"
            //~Student()
            //{
            //    Console.WriteLine("Destructor");
            //}

        }
        static void Main(string[] args)
        {
            Console.ReadKey();
        }
    }
}

Cannot initialize struct member inside a struct.

In a struct, we cannot initialize a 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
        {
            //Variables 'Roll_no', 'Name' and 'Mobile' are initialised with value which is not possible in struct.
            //It will produce a compile error as "Program.Student cannot have instance property or field initializers in structs"
            //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 a 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 the 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 structure 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 }; // original
var struct2 = struct1; // A copy is made
var struct3 = struct2; // A copy is made
var struct4 = struct3; // A copy is made
var struct5 = struct4; // A copy is made

// NOTE: A "copy" will occur when you pass a struct into a method parameter.
// To avoid the "copy", use the ref keyword.

// Although structs are designed to use less system resources
// 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.

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; // A reference is made to class1
var class3 = class2; // A reference is made to class1
var class4 = class3; // A reference is made to class1
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.

var struct1 = new IntStruct() { Value = 0 };
var struct2 = struct1;
struct2.Value = 1;
// At this point, a developer may be surprised when
// 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 a 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 structure 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.


Similar Articles