C# Structs

In the C# programming language, a struct (known as a structure) is like a class that is used to store data under a single unit. Structs are value types, which means that they are stored on the stack and passed by value rather than by reference. It contains many distinct data types , and it is a user-defined data type. It can include nested types, constants, fields, methods, properties, indexers, operators , events , and a parameterized or static constructor . The Struct is defined by the struct keyword.

Define a struct in C#

In C#, the structure can be defined using the struct keyword.

For Example:

Example

struct master

{

public int id;

}

Declare a struct Variable in C#

In C# programming , we must first declare a struct variable before using a struct. It is done by specifying the struct name followed by the variable name.

For Example:

Example

struct master {

  public int id;

}

. . .

// declare mst of the struct Employee

master mst;

Access the Struct Member in C#

The dot (.) operator is used to access the struct member. The examples are as given below.

For Example:

Example

struct Master {

  public int id;

}

... 

// declare mst of struct Master

Master mst;

// accessing the member  

mst.id = 1;

Here, we are using the mst variable with the dot (.) operator to access the members of the master.

Struct Example in C#

Let us take an example to define a struct in C#.

Example

Example

using System;

struct Person

{

    public string Name;

    public int Age;

    // Method inside struct

    public void DisplayInfo()

    {

        Console.WriteLine("The name is " + Name );

        Console.WriteLine("The age is " + Age );

    }

}

class Program

{

    static void Main()

    {

        // Declare and initialize struct variable

        Person p1;

        p1.Name = "Michael";

        p1.Age = 25;

        // Calling method

        p1.DisplayInfo();

    }

}

Output:

Output

The name is Michael

The age is 25

Explanation:

In this example, we create a struct named Person that contains two variables, name (string) and age (integer). After that, it defines the parameterised constructor to initialize these fields and the DisplayInfo method to print the details. In the main method, we create the object (p1) and call the DisplayInfo method to display the details.

struct Constructor in C#

In C#, we can create a constructor for a struct by defining it with the public keyword followed by the struct name.

Syntax:

It has the following syntax.

Example

struct StructName

{

    // Fields

    public int x;

    public int y;

    // Parameterized constructor

    public StructName( int a, int b )

    {

        x = a;

        y = b;

    }

}

Constructor in C# struct Example

Let us take an example to illustrate the struct using a Constructor.

Example

Example

using System;

struct Details

{

    public string name;

    public int age;

    // Constructor

    public Details( string na_me, int a_ge )

    {

        name = na_me;

        age = a_ge;

    }

    public void DisplayInfo()

    {

        Console.WriteLine("The name is: " + name + ", age: " + age );

    }

}

class Program

{

    static void Main()

    {

        // structure object

        Details d1 = new Details("Jhonson", 25);

        d1.DisplayInfo();

    }

}

Output:

Output

The name is: Jhonson, Age: 25

Explanation:

In this example, we create a struct named Person that contains two variables, name (string) and age (integer). After that, it defines the parameterised constructor to initialize these fields and the DisplayInfo method to print the details. In the main method, we create the object (p1) and call the DisplayInfo method to display the details.

Immutable Structure (struct)

In the C# programming language, a structure is said to be immutable if its state cannot be changed once it has been created. It means that no fields or properties of the struct can be modified after construction.

Example of Immutable Structure

Let us take an example to illustrate the immutable structure in C#.

Example

Example

using System;

struct Details {

    public readonly string name;

    public readonly string contact;

    public readonly string id;

    public Details( string name, string contact, string id ) {

        this.name = name;

        this.contact = contact;

        this.id = id;

    }

    public void ShowDetail() {

        Console.WriteLine($"Name: {name}, Contact: {contact}, ID: {id} ");

    }

}

class Program {

    static void Main() {

        Details d = new Details("Albert", "878283XXXX", "EMPO01");

        d.ShowDetail();

    }

}

Output:

Output

Name: Albert, Contact: 878283XXXX, ID: EMPO01

Explanation:

In this example, we define the immutable struct named Details that contains three readonly fields: name, contact, and id. After that, we create a parameterized constructor and set the value. The ShowDetails method displays these values. In the main method, create the object and call the ShowDetail method to print the details.

Array of Structures in C#

In C#, an array of structures allows us to store multiple instances of a structure in a single array. It can access the structure member using an array with a specific index.

Syntax:

It has the following syntax:

Example

Array[ index ].Structure( data );

In this syntax, an index is defined, the particular indexes of an array where the values are inserted or deleted, and the data are the values in the structure.

Array of Structure Example in C#

Let us take an example to illustrate the array of structure in C#.

Example

Example

using System;

public struct Emp

{

    // Declare variables

    public int Roll_No;

    public string Name;

    public int Age;

    // Set the employee details

    public void Set_Emp(int RollNo, string name, int age)

    {

        Roll_No = RollNo;

        Name = name;

        Age = age;

    }

    // Display employee details

    public void Display_Emp()

    {

        Console.WriteLine("Employee details: ");

        Console.WriteLine("Id: " + Roll_No);

        Console.WriteLine("Name: " + Name);

        Console.WriteLine("Age: " + Age);

        Console.WriteLine("\n");

    }

}

class TPT

{

    static void Main(string[] args)

    {

        // Create an array of Emp structs

        Emp[] e = {

            new Emp(),

            new Emp(),

            new Emp()

        };

        // Set values for each employee

        e[0].Set_Emp(1, "John", 50);

        e[1].Set_Emp(2, "Thomson", 31);

        e[2].Set_Emp(3, "David", 27);

        // Display employee details

        e[0].Display_Emp();       

        e[1].Display_Emp();

        e[2].Display_Emp();

    }

}

Output:

Output

Employee details: 

Id: 1

Name: John

Age: 50

Employee details: 

Id: 2

Name: Thomson

Age: 31

Employee details: 

Id: 3

Name: David

Age: 27

Explanation:

In this example, we define the struct named Emp that contains three variables: RollNo, Name, and Age. We also contain two methods: SetEmp to assign values and DisplayEmp to show the details of the employee. In the main method, an array of three Emp structures is created and initialized using the SetEmp method. After that, the program shows each employee's details using the Display_Emp method.

Properties in C# Struct

In the C# programming language, the properties in a struct (structure) are used to encapsulate and manage access to the fields of the struct. Just like in classes, structs can also have properties with get and set accessors, and they can also be read-only.

Properties Struct Example in C#

Let us take an example to illustrate the Struct property in C#.

Example

Example

using System;

namespace Struct {

  // declare the struct

  struct Stu_dent {

    public int id;

    // define property

    public int Id {

      get {

        return id;

      }

      // sets the value

      set {

        id = value;

      }

    }

  }

  class Program {

    static void Main(string[] args) {

      // Invoke the Constructor 

      Stu_dent std = new Stu_dent();

      std.Id = 1;

      Console.WriteLine("Student Id: " + std.Id);

      Console.ReadLine();

    }

  }

}

Output:

Output

Student Id: 1

Explanation:

In this example, we have taken a struct named Stu_dent that is defined with a private field id and a public property Id that provides controlled access to it using get and set accessors. In the main method, an instance of the struct is created, the Id property is assigned a value, and then the result is displayed.

Difference between the Structure and Class

There are several differences between the structure and class in C#. Some main differences are as follows:

Structure Class
Structure is a value type. Class is a reference type.
Inheritance is not supported in the structure. Inheritance is supported in class.
Structure is defined by the struct keyword. The class is defined by the class keyword.
The structure members are public by default. The class members are private by default.
The syntax of the structure is.Struct StructName {datatype m1;datatype m2;}; The syntax of the class is.Class ClassName {// data member// data method};

Features of C# Structure:

Several features of the C# Structure are as follows.

  • The structure can have methods, properties, indexers, fields, operator methods, and events.
  • It can also include parameterized constructors, constants, enumerations, and nested types.
  • A structure is a value type, which means that it is stored on the stack and passed by value.
  • A structure can be implemented with one or more interfaces.
  • Struct members cannot be protected, virtual, or abstract.
  • Conclusion

In conclusion, C# structure (struct) is an essential concept for any developer creating a software application. It is the main objective of the development. A struct is like a class that is used to store data under a single unit. It is a value type. It contains many distinct data types. It contains several methods, properties, indexers, fields, operator methods, and events.

C# struct FAQs

1) What is the struct in C#?

In the C# programming language, a struct (known as a structure) is like a class that is used to store data under a single unit. Structs are value types, which means they are stored on the stack and passed by value rather than by reference. It contains many distinct data types, and it is a user-defined data type.

2) Can we define the Constructor in C#?

Yes, we can define the parameterised constructor in C#

3) Do structs support inheritance in C#?

The structs do not support inheritance. It cannot be inherited by the other classes or structures.

4) What is the difference between structs and classes in C#?

The main difference between structs and classes is that structs are value types that are kept on the stack, while classes are reference types that are stored on the heap.

5) Why would we use a struct instead of a class?

When we need a lightweight object to represent a small amount of data, we can utilize a struct. It is more memory efficient than classes because they are value types, which are stored on the stack.

Input Required

This code uses input(). Please provide values below: