C# Struct with [Examples]

C# Struct: A struct in C# is a value type that represents a lightweight object. It is similar to a class but stored on the stack rather than the heap. A struct is faster to create and use than a class. It is useful when you want to create small, lightweight objects to hold value-type data rather than a reference type.

It is also useful when you want to create mutable objects (that can be modified after they are created).

Structs have some limitations compared to classes. For example, structs cannot be inherited from other structs or classes. It also does not support some advanced features that classes support, such as virtual methods and polymorphism.

CSharp-Struct
C# Struct

Define struct in C#

In C#, we can use the struct keyword to define a struct. For example:

struct Employee  {
  public int Name;
}

Here, the Name is a field inside the struct. A struct can include Fields, methods, indexers, etc.

Key points about Struct in C#

Following are some essential points about structures in C#:

  • Structs are value types, meaning they are stored on the stack instead of the heap. That makes them faster to create and use than reference types, such as classes.
  •  Struct does not support inheritance. A struct cannot inherit from another struct or class and cannot be used as a base class.
  •  A struct can have constructors, fields, methods, properties, and other members like classes. However, it cannot have destructors or finalizers.
  •  We can create a struct object with or without the new operator, similar to primitive type variables.
  •  A Struct is typically used to represent a small, simple object and to store value-type data rather than reference. For example: such as points, rectangles, and complex numbers.
  •  Structures are mutable, meaning you can change their fields and properties after they are created.
  •  Structures are value-type or value-based, which means they are compared by their contents rather than by their reference.
  •  In C#, Structures can be created using the struct keyword.
  •  Although Structure does not support inheritance, it can still be implemented using interfaces.
  •  Struct members cannot be marked as abstract, virtual, sealed, or protected.

Example: C# Struct

In C#, you can declare a structure using the struct keyword followed by the name of the struct. Here is an example of a simple struct declaration in C#:

struct Point
{
    public int X;
    public int Y;
}

In the above code example, we have declared a new struct called Point that has two public fields: X and Y, which represent the x and y coordinates of a point on a two-dimensional plane.

Access C# struct

To access a struct in C#, you will first need to create an instance of the struct by using the new keyword, followed by the name of the struct. For example:

// Define struct
struct MyStruct {
  public string Name;
}
// Create instance
MyStruct struct = new MyStruct();

Once you have an instance of the struct, you can access its members (fields, properties, and methods) using the dot (.) operator.

Here, we have used the variable struct of a struct MyStruct with a dot (.) operator to access the member Name of the MyStruct. For example:

// Access struct member
struct.Name = "Shekh Ali";
string result = struct.Name;

C# Struct Example: Using Constructor and Method

You can also add constructors, methods, properties, and other members to a struct just like you would with a class. In the following code example, we create a new struct instance using the new operator and a constructor.

using System;
namespace StructExample
{
    struct Point
    {
        // Fields
        public int X;
        public int Y;

        // Constructor
        public Point(int x, int y)
        {
            X = x;
            Y = y;
        }
        // Method
        public double CalculateDistanceToOrigin()
        {
            return Math.Sqrt(X * X + Y * Y);
        }
    }

    class Program
    { 
        static void Main(string[] args)
        {
            Point p1 = new Point(1, 2);
            Point p2 = new Point(3, 4);

            double point1 = p1.CalculateDistanceToOrigin();
            double point2 = p2.CalculateDistanceToOrigin();
            Console.WriteLine($" Point1 : {point1} , Point2: {point2}");
            Console.ReadKey();
        }      
    }
}

In this above code example, we added a constructor to the Point struct that allows us to create a new Point object and initialize its X and Y fields. We also added a method called CalculateDistanceToOrigin that calculates the distance of the point from the origin (0, 0).

We have created two new Point objects p1 & p2 with the coordinates (1, 2) and (3, 4), respectively. We then access the fields and methods of the struct using the dot operator (.).

Once we run the code, we will get the following result:

Point1 : 2.23606797749979 , Point2: 5

C# Struct with Default Constructor

The struct in C# prevents us from declaring a default constructor or a parameterless constructor. It doesn’t allow us to initialize fields with values unless they are marked as const or static.

struct Person
    {
        // Compile time error
        public string name = "Shekh Ali";

        public int age;

        // Compile time error
        public Person()
        {        
            age = 32;
        }
     }

C# Struct without the new keyword

We can create a struct object with or without the new keyword, similar to primitive type variables.
In the following code example, we create a struct named Person without a new operator.

using System;
namespace StructExample
{
    // Defining structure
    public struct Person
    {
        // Declaring fields with different data types
        public string Name;
        public int Age;
    }
    class Program
    {
        // Main Method
        static void Main(string[] args)
        {
            // Declare P1 of type Person
            Person Person1;

            // Person1 data
            Person1.Name = "Shekh Ali";
            Person1.Age = 28;

            // Declare Person2 of type Person
            Person Person2;

            // Person2 data
            Person2.Name = "Roman";
            Person2.Age = 30;

            // Displaying the values of Person1
            Console.WriteLine("*** Values Stored in Person1 ***");
            Console.WriteLine($" Name: {Person1.Name}");
            Console.WriteLine($" Age: {Person1.Age}");
          
            Console.WriteLine("");
            // Displaying the values of Person2
            Console.WriteLine("*** Values Stored in Person2 ***");
            Console.WriteLine($" Name: {Person2.Name}");
            Console.WriteLine($" Age: {Person2.Age}");
            Console.ReadKey();
        }
    }
}

The output of the above program is as follows:

*** Values Stored in Person1 ***
Name: Shekh Ali
Age: 28

*** Values Stored in Person2 ***
Name: Roman
Age: 30

Suppose you do not use the new keyword when declaring a structure type variable. In that case, the default constructor will not be called, and the structure members will not be assigned any values. As a result, you will encounter a compile-time error.
So, you must assign values to each member of the structure before accessing them.

Can a struct have events in C#?

A struct can have events in C# just like a class. Events provide a way for the struct to notify other objects when something happens or changes within the struct.

Example: Event in Struct

Here is an example of a struct with an event in C#:

using System;
namespace StructWithEventExample
{
    struct Point
    {   
        public event Action<int,string> Moved;

        private int x;
        private int y;

        public int X
        {
            get { return x; }
            set
            {
                x = value;
                Moved?.Invoke(x,"X");
            }
        }

        public int Y
        {
            get { return y; }
            set
            {
                y = value;
                Moved?.Invoke(y,"Y");
            }
        }
       
    }

    class Program
    {
        private static void OnPointMoved(int value, string Cord)
        {          
            Console.WriteLine($"Coordinate {Cord}: changed to {value} ");
        }
        static void Main(string[] args)
        {
            Point p = new Point();
            p.Moved += OnPointMoved;
            p.X = 5;
            p.Y = 10;
            Console.ReadKey();
        }
    }
}

In the above code example, the Point struct has two fields, x, and y, representing the point coordinates. It also has two properties, X and Y, that provide access to these fields.

The setters of these properties invoke the Moved event to notify other objects whenever the point coordinates are changed.
To use the Point struct, you can create an instance of it and subscribe to the Moved event:
Then, you can define the OnPointMoved event handler to handle the Moved event:

The output of the above program is as follows:

An event in struct example

Difference between struct and class in C#

Here is a list of differences between struct and class in C#:

  1. Definition: A struct is a value type, while a class is a reference type.
  2.  Memory allocation: In C#, the Stack memory stores a struct object, while a class object is stored on the heap memory. However, a reference to the heap memory is stored on the Stack.
  3.  Default member accessibility: The members of a struct are public by default, whereas the members of a class are private by default.
  4.  Inheritance: A struct cannot inherit from another struct or class, while a class can inherit from another class in C#.
  5.  Destructors: A struct does not support destructors or finalizers. At the same time, a class can have a destructor or finalizer to clean up resources before the object is garbage collected.
  6.  Nullability: A reference type (such as a class) can be assigned a null value, while a value type (such as a struct) cannot.
  7. Performance: Structs perform better than classes due to their value type nature and faster memory allocation on the Stack.

FAQ

The following are some frequently asked questions and answers about struct in C#:

Q: What is a struct in C#?

A: A struct in C# is a value type that represents a lightweight object. It is similar to a class but has some key differences such as memory allocation, default member accessibility, and inheritance. Structs are useful for representing small, simple objects that don’t require the overhead of a full-fledged class.

Q: How can you define a struct in C#?

A: To define a struct in C#, use the struct keyword followed by the name of the struct and a set of curly braces { } that contain the members of the struct. Following is an example of a struct:
struct Coordinate
{
public int X;
public int Y;
}

Q: Can a struct inherit from another struct or class in C#?

No, a struct cannot inherit from another struct or class in C#. A struct is a value type that cannot inherit from a reference type.

Q: Can a struct implement interfaces in C#?

Yes, a struct can implement interfaces in C#, just like a class. It allows a struct to define and implement the behaviors specified by the interface.

Q: What is the performance difference between a struct and a class in C#?

In general, structs can perform better than classes due to their value type nature and faster memory allocation on the stack.

Q: Can a struct be null in C#?

A: No, a struct cannot be assigned a null value in C# because it is a value type.

Q: Can a struct have a destructor or finalizer in C#?

No, a struct cannot have a destructor or finalizer in C#. Destructors and finalizers are used to clean up resources before an object is a garbage collected. Still, structs do not support garbage collection because they are value types. Instead, structs rely on their value-type nature to automatically reclaim their memory when they go out of scope or are no longer needed.

Q: Can a struct have properties in C#?

A struct can have properties in C# just like a class. Properties are a convenient way to encapsulate the data and behavior of a struct. We can use them to provide access to the underlying fields of the struct in a controlled and consistent way. Here is an example of a struct with a property:
// Defining structure
struct Coordinate
{
// private fields
private int x;
private int y;
//public Properties
public int X {
get { return x; }
set { x = value; }
}
public int Y
{ get { return y; }
set { y = value; }
}
}

Q: Can a struct have methods in C#?

A: Yes, a struct can have methods in C# just like a class.

Here are some recommended articles on collections:

References: MSDN-Structure type

Please share this post and let us know what you think in the comments.

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments