Looking for c# Answers? Try Ask4KnowledgeBase
Looking for c# Keywords? Try Ask4Keywords

C# Language Declaring a struct


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.