C# Error
CS8168 – Cannot return local ‘{0}’ by reference because it is not a ref local
Reason for the Error & Solution
Cannot return local by reference because it is not a ref local
Example
The following sample generates CS8168:
// CS8168.cs (8,14)
public class Test
{
ref char Test1()
{
char l = default(char);
return ref l;
}
}
The scope of l
is within the body of the method. If a reference to l
were to leave the scope of this method, that reference would outlive the object to which it refers. The compiler’s scope rules cause error CS8168 to be generated in this example.
To correct this error
To return the value of a local, refactoring to return by value will correct this error:
// CS8168.cs (8,14)
public class Test
{
char Test1()
{
char l = default(char);
return l;
}
}