Reputation: 3099
The following code doesn't compile with C# 7.0
/ Visual Studio 2017.2:
class C {
private static readonly int s = 5;
public static ref int Data => ref s;
}
Is there an technical reason for disallowing references on static readonly fields or is this just a missing feature?
The error message says:
CS8162: A static readonly field cannot returned by reference.
Upvotes: 2
Views: 993
Reputation: 8503
This is now possible in C# 7.2.
class C {
private static readonly int s = 5;
public static ref readonly int Data => ref s;
}
Upvotes: 4
Reputation: 43254
You can't yet return a reference to a readonly field, as ref returns are mutable. However, the ref readonly
feature is planned for a future version of C# (currently pencilled in for C# 7.2, but that may change).
This feature will likely address both the ability to return references to readonly fields, as well as allowing ref
parameters to be marked as readonly too, to offer the guarantee that the values referenced won't be modified by the method.
Upvotes: 3
Reputation: 887453
Because it's readonly
.
The point of ref
is to allow the referenced variable to be changed, which would violate readonly
.
Upvotes: 10