C# Records

C# Code Snippets Records


In this code snippetwe will take a look at records in C#.

Records can be used instead of classes and structs. They reduce the amount of boilerplate code required to create objects whose purpose is to simply hold data. By default, records are reference types just like classes but they will act like value types when compared for equality(using == operator) meaning that two different records will be evaluated as the same if all their values are the same.

If you were to look at the lowered code in the background you would see that the compiler actually turns a record into a class(or struct if you used record struct).

Let’s have a look at the code below to see how to use records.


var src1 = new MessageCls("Bob", "Hello.");
//A class record is readonly so this would throw an error at compile time.
//src1.value = 144; 

//If you want to modify a record you can do it like so.
var modified_src1 = src1 with { message = "Bye." };

var src2 = new MessageCls("Bob", "Bye.");
var src3 = new MessageCls("Bob", "Bye.");

Console.WriteLine(src2 == src3); //This will be True bacause records have value based equality.

var srs1 = new MessageStr("Alice", "Hello.");
//With struct records you can modify the value.
srs1.message = "Bye.";

var srs2 = new MessageStr("Alice", "Bye.");
var srs3 = new MessageStr("Alice", "Bye.");

Console.WriteLine(srs2 == srs3);


//By default a record will be a class record.
record MessageCls(string byUser, string message);

//If you want a record struct you have to specify that.
record struct MessageStr(string byUser, string message);

Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger