Author : MD TAREQ HASSAN | Updated : 2021/03/22
Struct in CSharp
- A struct type is a value type that is typically used to encapsulate small groups of related variables
- It is an error to define a parameterless constructor for a struct
- It is also an error to initialize an instance field in a struct body
- Unlike classes, structs can be instantiated without using the new operator. In such a case, there is no constructor call, which makes the allocation more efficient. However, the fields will remain unassigned and the object cannot be used until all of the fields are initialized
- If you instantiate a struct object using the parameterless constructor, all members are assigned according to their default values.
- When writing a constructor with parameters for a struct, you must explicitly initialize all members; otherwise one or more members remain unassigned and the struct cannot be used, producing compiler error CS0171.
- Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.
- Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.
- Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
- A struct cannot be null, and a struct variable cannot be assigned null unless the variable is declared as a nullable value type.
- struct (C# Reference)
Syntax
public struct Coords
{
public int x, y;
public Coords(int p1, int p2)
{
x = p1;
y = p2;
}
}