Record is immutable at compile time but it's not at runtime. #3904
-
Using Net 5 Rc1 and Creating a record: public record Rectangle
{
public int Width { get; init; }
public int Height { get; init; }
} Then instantiating it: var rectangle = new Rectangle (20,30); Trying to change the value:
Compiler raise the error:
That is right and insure that the record is immutable. Using a method like to test IsImmutable type give false, because in record there is no generated readonly properties. How to check the record in c# 9 is immutable at runtime or even it's record with |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 4 replies
-
A record is indeed mutable at runtime. This is intentional, is it means most serializer frameworks work without updating. It is however possible to check if a property is init by checking:
|
Beta Was this translation helpful? Give feedback.
-
Thanks @YairHalberstadt for answer. |
Beta Was this translation helpful? Give feedback.
-
Now, it returns true :) for both properties. |
Beta Was this translation helpful? Give feedback.
-
Thank you @YairHalberstadt for help and support. |
Beta Was this translation helpful? Give feedback.
-
@333fred |
Beta Was this translation helpful? Give feedback.
A record is indeed mutable at runtime. This is intentional, is it means most serializer frameworks work without updating.
It is however possible to check if a property is init by checking: