c sharp

How to Use Struct in C#

In C#, a struct is a value type that encapsulates a group of related data members. It is a lightweight alternative to a class and can be used for storing small amounts of data that do not require inheritance or reference type semantics. This post will explain what is a struct in C# along with its syntax and will illustrate its use with the help of examples.

What is struct in C#

A struct is a simple class that is allocated on the stack instead of the heap. A struct declaration can include fields, properties, nested types, indexers, methods, and operators. A struct can also implement one or more interfaces. Unlike a class, a struct cannot inherit from another struct or class and cannot be used as a base class. The syntax for declaring a struct in C#:

struct structName

{

    // Fields and methods

}

How to Use struct in C#

The following code example demonstrates the declaration and usage of a struct:

using System;

struct Point {

  public int X;
  public int Y;

  public Point(int x, int y) {
    X = x;
    Y = y;
  }
  public void Display() {
    Console.WriteLine("X = {0}, Y = {1}", X, Y);
  }
}
class Program {
  static void Main(string[] args) {
    Point p1 = new Point(10, 20);
    Point p2 = new Point(30, 40);
    p1.Display();
    p2.Display();
    Console.ReadLine();
  }


}

In this example, we define a struct called “Point” with the fields (X and Y) initialized in its constructor. The struct also has a method called “Display” that prints the values of the X and Y fields. In the Main method, we create two Point structs and call the Display() method on each one.

A struct can be more effective in terms of memory use and efficiency than a class, which is one benefit of utilizing one instead of the latter. This is because a struct is allocated on the stack instead of the heap, which can be faster for small objects that are frequently created and destroyed. However, using a struct can also have disadvantages, such as limited support for inheritance and more limited functionality compared to classes.

Conclusion

A struct in C# is a value type that can be used for storing small amounts of data that do not require inheritance or reference type semantics. Structs are declared using the “struct” keyword and can include fields, properties, nested types, indexers, methods, and operators. Structs can be more efficient than classes in some cases but also have some limitations.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.