SoFunction
Updated on 2025-03-01

C# Introduction to Struct

Overview:

The structure is similar to a class, but the structure is a value type and is stored on the stack.

Structures cannot be inherited or inherited, but interfaces can be implemented.

The access levels of structure members include public, private (default), and internal.

1. Simple structure

Simple classes such as no methods and attributes can be declared as structures to improve system processing efficiency.

Define the structure type:

struct Pair
{
    public int x;
    public string y;
}

Called:

Pair p;//New can only be omitted when only fields exist in the structure.Pair P1 = new Pair();
 = 10;
 = "a";
();

2. Structure with constructor

Structures can customize constructors with parameters and must display initialization of all instance fields. The default constructor is not displayed.

void Main()
{
    Pair P1 = new Pair(10);
    (1);
    ();
}

struct Pair
{
    private int x;//Instance fields cannot be assigned when declared (that is, they cannot be initialized)    private static Pair orign = new Pair();// Static fields can be assigned values ​​when declared
    public Pair(int x)//Constructor    {
         = x;
    }
    public int X //The structure can have attributes    {
        set { x = value; }
        get { return x; }
    }
    public void Add(int y)//There can be methods for the structure    {
        x = x + y;
    }
}

This is all about this article about the introduction to C# structure type Struct. I hope it will be helpful to everyone's learning and I hope everyone will support me more.