C# Error CS8168 – Cannot return local ‘{0}’ by reference because it is not a ref local

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;
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...