In this tutorial we will explore the structure type, the circumstances they may be used in and how you would go about creating one.
We introduced Structs in a previous tutorial, we established that they a value type that can encapsulate data and functionality. This is similar to a class, however, classes are reference types whereas structs are value types.
Structs cannot support inheritance, nor can they have parameterless constructors, finalisers, virtual members and field initialisers.
For these reasons, structs are best suited to cases where the data structure is kept small and only containing primitive data types with limited behaviour.
Due to a struct being a value type it is also recommended that you do not change the members of the struct after declaration. More information about this can be found at the Microsoft Documentation for Structs :
When you define a structure you must assign a value to every field and not just some of them. Structs also do not support field initialisers, i.e. assigning a default value to members when a struct is created, attempt to do so will result in an error being thrown.
using System;
public struct TestStruct
{
public int a;
public int b;
public TestStruct(int a, int b)
{
this.a = a;
this.b = b;
}
}
public class Program
{
public static void Main()
{
TestStruct testStruct = new TestStruct(1,2);
Console.WriteLine(testStruct.a);
}
}