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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...