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();
}
}
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"