C# Struct: Understanding Structure in C# With Examples

C# Struct: A struct in C# is a value type that represents a lightweight object. It is similar to a class but is stored on the stack rather than on the heap. This means that a struct is faster to create and use than a class.

Struct 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 objects that are mutable (that can be modified after they are created) because structs are stored on the stack and can be modified directly.

However, structs have some limitations compared to classes. For example, structs cannot be inherited from other structs or classes, and they do not support some of the advanced features that classes support, such as virtual methods and polymorphism.

CSharp-Struct
c# struct

Important points about structure in C#

Following are some important points about structures in C#:

  • Structures are value types, which means that they are stored on the stack instead of the heap. This makes them faster to create and use than reference types, such as classes.
  • Structures do not support inheritance. A struct cannot inherit from another struct or class, and it cannot be used as a base class.
  • A struct can have constructors, fields, methods, properties, and other members just like classes. However, it cannot have destructors or finalizers.
  • A struct object can be created with or without the new operator, similar to primitive type variables.
  • A struct or Structure is typically used to represent a small, simple object that is passed around by value rather than by reference. For example: such as points, rectangles, and complex numbers.
  • Structures are mutable, which means that you can change their fields and properties after they are created.
  • Structures are value-type or value-based, which means that 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.

Define struct in C#

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 are creating a new instance of the struct 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 are creating 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

If you do not use the new keyword when declaring a variable of a structure type, the default constructor will not be called and the members of the structure 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#?

Yes, a struct can have events in C# just like a class. Events are used to 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 that represent the coordinates of the point. 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 coordinates of the point 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: When an object of a struct is created, memory is allocated on the stack. When an object of a class is created, memory is allocated on the heap, and a reference to that 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, while 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: In general, structs perform better than classes due to their value type nature and faster memory allocation on the stack. However, this is not always the case and can depend on various factors such as the size of the structure and the complexity of the operations being performed on it.

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#?

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

Q: Can a struct implement interfaces in C#?

A: Yes, a struct can implement interfaces in C#, just like a class. This 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#?

A: In general, structs can perform better than classes due to their value type nature and faster memory allocation on the stack. However, this is not always the case and can depend on various factors such as the size of the struct and the complexity of the operations being performed on it.

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#?

A: No, a struct cannot have a destructor or finalizer in C#. Destructors and finalizers are used to clean up resources before an object is garbage collected, but 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: Yes, 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 and can be used 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

If you enjoyed this post, please share it with your friends or leave a comment below.

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments