Organizing Data Using Records in C#
Arifuzzaman Tanin
Software Engineer | C# | .NET | React | Blazor | JavaScript | Full Stack | Azure | DevOps | Agile | Microservices | gRPC
What's a Record?
C# 9.0 introduces a powerful new feature called "records" (reference type) that revolutionizes the way developers handle immutable data types. Records are succinct, immutable data types that are designed to simplify code and increase productivity. You can read my other article on reference type. Here
So, imagine you have some data in your C# code that you don't want to change once you set it. Maybe it's some info about a person like their name, age, and country. A record in C# is like a special container just for that kind of info. It's super simple to use and helps keep things organized.
Why Do We Use Records?
Okay, picture this: you're making a program and you need to keep track of a bunch of stuff. Instead of writing a whole bunch of code to manage each piece of info, you can use a record. It's like a shortcut that saves you time and makes your code easier to read.
领英推荐
How Do We Use Records?
Let's get practical. Say we want to create a record to hold info about a person. Here's how easy it is:
public record Person
{
public string Name { get; init; }
public int Age { get; init; }
public string Country { get; init; }
}
Boom! That's it. We've just made a record called Person with three properties: Name, Age, and Country. And see those init things? They make sure we can only set these properties when we create a new Person object. Once it's set, it can't be changed. Simple, right?
Why It's Awesome
Records are awesome because they help us: