C# Language Structs Declaring a struct

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

public struct Vector 
{
    public int X;
    public int Y;
    public int Z;
}

public struct Point
{
    public decimal x, y;
    
    public Point(decimal pointX, decimal pointY)
    {
        x = pointX;
        y = pointY;
    }
}
  • struct instance fields can be set via a parametrized constructor or individually after struct construction.

  • Private members can only be initialized by the constructor.

  • struct defines a sealed type that implicitly inherits from System.ValueType.

  • Structs cannot inherit from any other type, but they can implement interfaces.

  • Structs are copied on assignment, meaning all data is copied to the new instance and changes to one of them are not reflected by the other.

  • A struct cannot be null, although it can used as a nullable type:

    Vector v1 = null; //illegal
    Vector? v2 = null; //OK
    Nullable<Vector> v3 = null // OK
    
  • Structs can be instantiated with or without using the new operator.

    //Both of these are acceptable
    Vector v1 = new Vector();
    v1.X = 1;
    v1.Y = 2;
    v1.Z = 3;
    
    Vector v2;
    v2.X = 1;
    v2.Y = 2;
    v2.Z = 3;
    

    However, the new operator must be used in order to use an initializer:

    Vector v1 = new MyStruct { X=1, Y=2, Z=3 }; // OK
    Vector v2 { X=1, Y=2, Z=3 }; // illegal
    

A struct can declare everything a class can declare, with a few exceptions:

  • A struct cannot declare a parameterless constructor. struct instance fields can be set via a parameterized constructor or individually after struct construction. Private members can only be initialized by the constructor.
  • A struct cannot declare members as protected, since it is implicitly sealed.
  • Struct fields can only be initialized if they are const or static.


Got any C# Language Question?