I found a great post by wrijugh.
Wriju explains the new C# Record Type.
I am excited about this feature, but I'm not 100% sure when I should use it and when I should stick to a class. Mads Torgersen provided some insights there in his presentation on C# 9 during the .net conference but I'm actually more interested in the practical side.
How do you plan on using this new feature? Do you think there are issues one has to think about when one uses the new Record Type? Do you think Record Types should be used for deserialization of a json string? Are you going to migrate from classes to Record Types?
Let me know in the comments :)!
Top comments (5)
Hi!
Records will be really useful in cases where we are looking for immutable data. Examples:
I recommend you to read this blog post (pre-records) by Jimmy Bogard when he explains the challenges of immutable classes in .net. Know, with records, it's embedded in the language.
jimmybogard.com/immutability-in-dtos/
Hi,
thanks for the comment! I agree records can be great for DTOs and Commands (I'm also thinking about MediatR). As Jimmy Bogard mentioned in his blog post upon until now Immutable objects could not be serialized easily. Now that we have records they are immutable and can be serialized π. Here is a small example of the serialization (I couldn't believe it, I had to try it myself :D) dotnetfiddle.net/e8tSIN
Agree with that. Kind of like what I do with kotlin and java. Data stuff is data class (record in C# and java). Services and others are class so it can mutate itself. In Java I just make stuff final if it's not used by some naggy framework until records are stable
Hi Ninja,
Thanks for the comment. What you said makes a lot of sense to me: if you need to move data from one to another use a
record
.IMHO records could also become a bit of a pain, if not used correctly. Think about this:
I think records could be also really helpful to serialize and deserialize stuff (because it reduces the lines of code by a lot).
I totally agree. IMHO, immutability should be the default and mutable properties should be used with caution. This also means I prefer having readonly collections whenever possible.