Record types are a new (as of .NET 5) data holding type in C#. They are immutable structures that are meant to hold data.
public enum Language
{
CSharp,
JavaScript,
Rust,
Go,
Python,
Java
}
public record Developer
{
public string FirstName { get; }
public string LastName { get; }
public Language Language { get; }
public Developer(string firstName, string lastName, Language language) =>
(FirstName, LastName, Language) = (firstName, lastName, language);
}
static void Main(string[] args)
{
Developer dev = new Developer("Ben", "Brougher", Language.CSharp);
Developer impostor = new Developer("Ben", "Brougher", Language.CSharp);
Console.WriteLine(dev == impostor ? "He got away with it" : $"Not today {impostor.FirstName}!");
}
This will output "He got away with it" and if you change any of the values in the impostor
variable it will print the other string
Developer dev = new Developer("Ben", "Brougher", Language.CSharp);
Console.WriteLine(dev);
yeilds the following in the console:
Developer { FirstName = Ben, LastName = Brougher, Language = CSharp }
there's a more concise way to specify a record if it is simply a data holding class:
//public record Developer
//{
// public string FirstName { get; }
// public string LastName { get; }
// public Language Language { get; }
// public Developer(string firstName, string lastName, Language language) =>
// (FirstName, LastName, Language) = (firstName, lastName, language);
//}
public record Developer(string FirstName, string LastName, Language language);
These two are equivalent.
You can also have methods in a positional record:
public record Developer(string FirstName, string LastName, Language Language)
{
public void WriteCode() =>
Console.WriteLine($"{FirstName} is writing a lot of cool code");
}
You can't modify a record by default, but you can create a new one with a new value:
Developer dev = new Developer("Ben", "Brougher", Language.CSharp);
Developer devWithNewLang = dev with { Language = Language.Rust };