Search code examples
c#returnrefc#-7.0

Why can't I ref return a static readonly field?


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.


Solution

  • Because it's readonly.

    The point of ref is to allow the referenced variable to be changed, which would violate readonly.