Wednesday, December 4, 2019

What's new in C# 8 Read-Only Members


     You've probably heard about the hype about the new C# 8.0 language standards being released earlier this year. This post and the following posts will serve as brief, informative overviews of the new language features that you can look forward to in the coming months.

      Read-only members are reserved for members that do not modify state. This keyword informs the compiler to enforce this principle. For example, if you wanted to implement a read-only member, you could write:

public readonly override string ToString() => $"({X}, {Y}) is {Distance} from the origin";

The following code would be incorrect:
public readonly void Translate(int xOffset, int yOffset) { X += xOffset; Y += yOffset; }
Why? You ask. Because you are modifying variables. One thing to note: Omitting a setter in a property does NOT automatically translate to a read-only property (in the sense that the compiler will not enforce the read-only rule)

The read-only modifier is only valid on struct members only.
Ideally, this feature gives you two advantages.

1. Enforcing intent
2. Performance optimizations

The performance optimization comes into play when you have a struct that is passed by reference. In this scenario, the compiler must generate a defensive copy of the state of the struct if it might be modified. If only the read-only members are accessed, the compiler doesn't need to create that defensive copy.
Besides enforcing intent, the compiler will not generate a defensive copy

No comments:

Post a Comment

New Features in .Net 10

🚀 Runtime Enhancements Stack Allocation for Small Arrays The Just-In-Time (JIT) compiler now optimizes memory usage by stack-allocating s...