C#

How to create struct in C#

ยท 1 min read

Like Enumerations, struct is value type, which means if you create a struct variable which holds its actual value not the reference. If you try to modify the value and it will not affect the other copy. Features of the Struct:

  • Immutable
  • Value type
  • suitable for collection of data (i.e. a list of weapons)

One of simple examples showing how to create and use struct:

// define a struct 
public struct Player {
	public int Level;
	public float XP;
}

// use struct
Player player = new Player();
player.Level = 1;
player.XP = 0;

Update

Like many other languages, struct in C# supports methods as well.

struct Car {
  public string Name;
  public EngineType Engine;
  public string Color;

  public double Speed {
    get {
      Console.WriteLine(_speed);
      return _speed;
    }
    set {
      _speed = value;
      Console.WriteLine(value);
    }
  }

  private double _speed;

  public void setInsuranceType() {
    Console.WriteLine("setup insurance");
  }

}

P.S. Bad practice of using Struct:

  • Struct variable will be used as value type in the most of time. So it is not recommended to have the reference type as the property in a Struct.
  • A struct variable should be less than 16 bytes