How do I enforce readonlyness of ref readonly in C# 7.2?

1k views Asked by At

I want to write a method returning ref a ref readonly as described: "The feature allows a member to return variables by reference without exposing them to mutations."

Unfortunately, my code compiles and does such a mutation. How do I make sure it cannot be modified? It is readonly for good reasons. I expect a compiler error. Should I doe something in addition? 200 is modified to 201. I do not want that.

internal class TryClass
{
    private static int _result = 0;

    public static ref readonly int Multiply(int a, int b)
    {
        _result = a * b;
        return ref _result;
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        int x = 10;
        int y = 20;
        var rez = TryClass.Multiply(x, y);
        rez++;
        Console.WriteLine(rez);
        Console.ReadLine();
    }
}
1

There are 1 answers

5
Daan On BEST ANSWER

Based on the comments. This is is the solution. I get the compiler error I expect: "Severity Code Description Project File Line Suppression State Error CS8329 Cannot use method 'TryClass.Multiply(int, int)' as a ref or out value because it is a readonly variable"

internal class Program
{
    private static void Main(string[] args)
    {
        int x = 10;
        int y = 20;
        ref readonly var rez = ref TryClass.Multiply(x, y);
        rez++;
        Console.WriteLine(rez);
        TryClass.DoAfter();
        Console.ReadLine();
    }
}