Struct keyword


In this article we are going to discuss about Struct keyword with examples in C#.

Struct Introduction

A struct (short for structure) is a value type in C# that is typically used to encapsulate small groups of related variables, especially when the data is not intended to be modified after the struct is created.

struct can be used to hold small data values that do not require inheritance, e.g. coordinate points, key-value pairs, and complex data structure.

Here is an example of how to define and use a struct in C#

using System;

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

    // Constructor to initialize fields
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    // Method to display the point
    public void Display()
    {
        Console.WriteLine($"Point: ({X}, {Y})");
    }
}

class Program
{
    static void Main()
    {
        // Create an instance of the struct
        Point p1 = new Point(10, 20);
        
        // Access struct members
        p1.Display();
        
        // Value type behavior
        Point p2 = p1;
        p2 = new Point(30, 40);
        
        // p1 remains unchanged
        p1.Display();
        p2.Display();
    }
}

Output

Struct Keyword in C#

Struct Constructor

Struct constructors must initialize all fields. You cannot define a constructor without parameter for a struct because a default parameterless constructor is provided automatically by the compiler. Here is a basic overview of how to define and use constructors within a struct in C#:

  1. Default Constructor - Structs always have a default parameterless constructor that initializes the fields to their default values (e.g., 0 for int, null for object references). This constructor is implicitly provided and cannot be explicitly defined.

  2. Parameterized Constructor - You can define constructors with parameters to initialize the fields of the struct.

Here is an example of defining and using a struct with a parameterized constructor in C#

using System;

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

    // Parameterized constructor
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public override string ToString()
    {
        return $"Point({X}, {Y})";
    }
}

public class Program
{
    public static void Main()
    {
        // Using the parameterized constructor
        Point p1 = new Point(10, 20);
        Console.WriteLine(p1);

        // Using the default constructor
        Point p2 = new Point();
        Console.WriteLine(p2);
    }
}

In the Main method, a Point object is created using the parameterized constructor and another one using the default constructor.

Output

Struct Keyword in C#

When to Use Struct and Class

  • Class - Use when you need complex behavior, inheritance, polymorphism, or large data structures that should not be copied.
  • Struct - Use for small, lightweight objects that represent a single value or concept (e.g., Point, Color) and do not require inheritance or polymorphism.

Predefined structs in the .NET Framework

C# includes several predefined structs in the .NET Framework that are commonly used. These structs are part of the System namespace and other related namespaces. Here are some of the most frequently used predefined structs in C#.

  1. System.Int32 - Represents a 32-bit signed integer.

    int number =42;

  2. System.Double - Represents a double-precision floating-point number.

    double pi = 3.14159;


  3. System.Boolean - Represents a boolean value (true or false).

    bool isTrue = true;
     
  4. System.DateTime - Represents an instant in time, typically expressed as a date and time of day.

    DateTime now = DateTime.Now;

When to Use Structs

  • Small Data Structures - Structs are ideal for small data structures that have a limited number of fields.
  • Immutability - When you want to create an immutable type where the state cannot change after creation.
  • Performance - When you need to optimize for performance and reduce heap allocations, especially for small, short-lived objects.

When Not to Use Structs

  • Complex Data Structures - For large and complex data structures, classes are generally more appropriate due to the overhead associated with copying structs.
  • Polymorphism - If you need to take advantage of inheritance and polymorphism, you should use classes.
  • Mutable State - If you need to modify the state of an object after it is created, classes are a better choice.

When to Prefer Structs Over Classes

  1. Small Data Types - Use structs for small, simple data types with a limited number of fields. Examples include a point in 2D space, a color, or a date. Structs are well-suited to scenarios where you need lightweight and efficient value types.

  2. Immutability Requirements - When you need to create immutable types where instances are not meant to change after creation, structs are a good fit. Immutable structs help ensure consistency and make the code more predictable.

  3. High Performance Scenarios - When performance is critical and you are dealing with many small instances, structs can provide better performance due to stack allocation and reduced garbage collection.

  4. Value Semantics - When you want to ensure that each instance of a type is independent and changes to one instance do not affect others, structs provide value semantics that achieve this.


Prev Next