Types are the building blocks in any programming language. C# is no different. Over the years, it has accumulated a variety of different types that a programmer can use to accomplish their goal. However, knowing what to use and when is essential if you really want to efficiently use the tools that are available to you. Everyone is aware of the classic class type but what about records? structs? or record structs? Let’s go through some examples, definitions, and use cases where you might use each of them.
Some Key Definitions
Let’s quickly go through some basic definitions which will help us categorize and differentiate the type.
Reference vs Value
The biggest difference between these types is whether they are reference types or value types. A reference type means that once an object has been instantiated and it needs to be passed around, a reference of the object is used. Meaning that in memory the original object stays as it is. On the other hand, a value type is something which when passed around creates new copies of itself. Any change in one will not affect the other ones.
For reference types, two objects are equal if they refer to the same object in memory.
For value types, two objects are equal if they are of the same type and store the same values.
Classes
Records
From Microsoft docs
You use the record modifier to define a reference type that provides built-in functionality for encapsulating data.
Key Features
- Reference type
- Immutable by default
- Value equality
- Built-in formatting for display
public record Person
{
public required string FirstName { get; init; }
public required string LastName { get; init; }
};
The following is a shorthand way of defining the same record as the one above. Both properties are automatically marked as required and immutable.
public record Person(string FirstName, string LastName);
References
- https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record
- https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/class