Categories
C#

record type in c#9

C# 9 is supported only on .NET 5 and newer versions and you will need to update your Visual Studio 2019 to 16.8 or later. To use C# 9 in existing .net core 3.x projects you can simply right click on Project > select Edit Project File and change target framework to net5.0

<TargetFramework>net5.0</TargetFramework>

Why would i want to use record instead of a class?

Records just generate classes under the hood, they also serialise just like any other type. Use record when you need to have value type but structs don’t really cut for you. You can use records anywhere you can use classes. Records uses value semantics for equality and they are immutable. There are some gotchas that we will cover shortly.

    public record Animal
    {
        public string Name { get; init; }

        public void Sleep()
        {
            Console.WriteLine("Zzzzzz");
        }
    }

    public record Mouse : Animal
    {
        public string Noise { get; init;} = "Squeek";
        public string FavoriteFood { get; init; } = "Cheese";
    }

Records can have constructors just like classes, you can define the constructor right after the record name and it will generate the members automatically.

    public record Animal(string Name)
    {
        public void Sleep()
        {
            Console.WriteLine("Zzzzzz");
        }
    }

    public record Mouse(string Noise = "Squeek",
                        string FavoriteFood = "Cheese",
                        string Name = "Stuart")
        : Animal(Name);
 // replace the body with semi-colon

    record Cat(string Color,
                string Name,
                string Sound = "Meow",
                string FavoriteFood = "Stuart") 
        : Animal(Name);

records also introduce the “with” expression, we can use the with expression to easily copy one object to another:

var mouse = new Mouse { Name = "Jerry" };
var mickeyMouse = mouse with { Name = "Mickey" };

With-expressions use object initializer syntax to state what’s different in the new object from the old object. You can specify multiple properties.

The ToString() method returns a comma-separated list of property names and values for all properties in the record type:

Mouse { Name = Jerry, Noise = Squeek, FavoriteFood = Cheese }

Value-based equality

Records do value based equality comparison by comparing each field of the record by calling .Equals on them recursively. Which means that based on the values two records can be equal without being the same object.

Gotchas

  • They are not supported by EFCore5 at the moment because records by nature are immutable, which means they cannot be changed, for EFCore5 we pull some data we make change to it and then we try to persist it but with record you can’t do that hence they are currently not supported.
  • Records cannot be inherited from classes.