Ian Ringrose
Ian Ringrose

Reputation: 51917

Other than an interview question when would 'readonly ref readonly` be used in C#?

I've just been told that readonly ref readonly is now valid C#, I can clearly see its use as an interview question, but otherwise when is it of real-life use?

Upvotes: 5

Views: 516

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

When you have a mutable struct in which you want to have a field ref readonly (a value you get by reference that cannot be modified by the caller) that does not mutate the struct.

You can find quite a good explanation here: "Readonly Ref vs Ref Readonly in C# Struct"

enter image description here

Now, as to "real-life" use cases... that's probably for performance-sensitive code, where copying the struct is too expensive.


Also, it's not really "new", it's possible to do this since C# 7.2: Microsoft Docs | Readonly references

Upvotes: 8

Related Questions