Structure in C#

Introduction

In C#, the structure is a user-defined data type which represents a data structure. We can also say that structure is a collection of different data types encapsulated into a single unit similar to a class. It is created or used for representing small objects.

In C# Structure is a value type so when we create an object of structure type, object instance will acquire memory on the Stack. Class Structure can contain constructors, constants, fields, events, indexers, methods etc.

To create a Structure, C# uses the struct keyword below is the syntax for creating structure

Syntax:

[<modifiers>] struct <structure name>
{
//The definition goes here
}

Let’s understand more by below code snippet example of Coordinate

public struct Coordinate
{
    public double Latitude;
    public double Longitude;
}

Use of the above Coordinate Structure

    static void Main()
    {
        Coordinate coordinate = new Coordinate
        {
            Latitude = 1201.11,
            Longitude = 12203.98
        };

        Console.WriteLine($"{coordinate.Latitude}");
        Console.WriteLine($"{coordinate.Longitude}");
        Console.ReadLine();
    }
}

In the above code snippet, we have created an instance of Coordinate using the new keyword. Suppose we have not used new keyword

class Program
{
    static void Main()
    {
        Coordinate coordinate;

        Console.WriteLine($"{coordinate.Latitude}");
        Console.WriteLine($"{coordinate.Longitude}");
        Console.ReadLine();
    }
}

The above code will give us compile-time error as have not used new keyword hence the variable value of “Coordinate” is unassigned, therefor we must assign the values each parameter before accessing those values.

Structure Members

  • Constructors – By default Structure has implicit type Constructor. explicitly we can define multiple constructors. However, Structure cannot contain explicit parameters less constructor. In C# if specifying any constructor then we have to assign values to all the variable otherwise we will get a compile-time error. Also, we cannot be specified Constructor as abstract, sealed, virtual, or protected.
  • Methods – We can add a method like the class. We can define public, private and internal methods only.
  • Events – Structures allows creating an event to raise different notifications to perform some of the action. As structures are value types, sometimes we might get failure while raising event as it is possible to subscribe to an event within a copy of a structure instance that later goes out of scope.
  • Constants – We can add constants and enumerations into the structure, but we cannot have specified them as abstract, sealed, virtual, or protected.
  • Variables- Variables defined within the code block of a structure that is available to all members of the structure. Variables can be declared as either public, private or internal. When structure instance created using new keyword by default value will be assigned to the variables (if explicitly not specified in constructor). if we try to access the variable value with creating new instance then the compile-time error will occur.
  • Indexers. A structure allows an indexer to provide enumeration functionality.

Example of structure with all members

public struct Coordinate
{
    private readonly double _latitude;
    private readonly double _longitude;
    private const int Ii = 100;
    private string _location;
    private delegate void Notify();

    private event Notify LocationFound;
    private readonly string[] _locations;

    private Coordinate(double latitude, double longitude) : this()
    {
        _latitude = latitude;
        _longitude = longitude;
        _location = "Spain";
        LocationFound = new Notify(OnLocationFound);
        _locations = new string[10];
    }

    public void Print()
    {
        Console.WriteLine($"{_latitude}-{_longitude}");
    }


    private void OnLocationFound()
    {
        LocationFound?.Invoke();
    }

    public string this[int index]
    {
        get
        {
            if (index < 0 || index >= _locations.Length)
                throw new IndexOutOfRangeException("Location out of Index.");

            return _locations[index];
        }
        set
        {
            if (index < 0 || index >= _locations.Length)
                throw new IndexOutOfRangeException("Location Index out of Range.");

            _locations[index] = value;
        }
    }

}

Points to remember

  • A structure can contain methods, constructors, constants, fields, properties, indexers, operators, events.
  • A structure member cannot be specified as abstract, sealed, virtual, or protected.
  • A structure cannot contain explicit parameters less constructor or a destructor.
  • A structure can implement interfaces, like a class.
  • A structure cannot be inherited by other structures, i.e. structures do not support inheritance.

Class Vs Structure

c# struct vs class. c# struct initialization ,c# when to use struct

When should I use a struct rather than a class in C#?


A struct provides some additional advantage like performance and resource utilisation over the class. So, When there is a lightweight class in the solution then instead of declaring them as the class it would be beneficial to write them as a struct. A struct will save memory as compare to class as in class both the data and the reference to that data must be stored when we create an instance of a class. Whereas struct does not store additional reference information. Also, the struct is value type so all value will be store on the stack so the compiler can access them directly but with a class object as its reference type compiler cannot access the value directly. Which can give performance gain over the class. It is always a good idea to use struct for a lightweight class.


Helpful resource

Leave a Reply

Your email address will not be published. Required fields are marked *