Classes are the blueprint of an object, defining its data, properties, and functionality. A class is also a custom type inside C-Sharp. A class template lies below:
Constructor
Constructors are called to instantiate an object passing initial values to the instance, using the new() method. It’s possible to use the default C# constructor or create a custom one inside a class.
A constructor is declared as a method inside the class, with the same name as its class, without a return type(not even void). It’s also possible to overload a constructor, changing its parameters.
To instantiate the object, the compiler will match the right constructor depending on the arguments passed.
One could also use a primary constructor, introduced in C# 12.
By convention, use Auto Properties , like the get and set keywords, for encapsulating or setting fields after instantiation.
Enumerations
The enum keyword creates Enumerations, which is used to store a set of named numeric constants variables. By default, they start from 0, incrementing by each member, even though it’s possible to assign a custom value.
It’s also possible to assign the value of a member, get the string and index value of a member, check if a string is defined by an enum object and finally, calling the member based on its value.
Structs
Similar to how classes are the blueprint of an object, structs are the blueprint of a custom data structure. Structs are similar to classes, but its data is stored as value instead of reference (like classes), which make them more lightweight. Actually, a struct is a value type in itself.
Additionally, structs can declare constructors, fields and methods, implementing an interface.
However, unlike classes, they can’t inherit or serve as base to another struct.
Records
Introduced in C# 9, records are reference types, very similar to classes, but they excel at encapsulating data. They are intended for storing immutable data and typically used to define simple data structures.
Records are ideal for read-only tasks, once the data cannot be changed after instantiated. While it’s possible to define methods, it’s not in a record use-case.
They also have value-based equality, whereas classes have memory-based. This translates to records being treated as equal if they present the same values, even if they’re not pointing to the same object in memory.
Interfaces
Interfaces are “blueprints” of a class, specifying the only required methods, properties, and parameters, widely used when implementing polymorphism. When creating a class using an interface, the compiler will ensure it follows every requirement from the interface.
Now, every class that inherits from the interface should define the properties and methods presented above.