C# Error CS8156 – An expression cannot be used in this context because it may not be passed or returned by reference

C# Error

CS8156 – An expression cannot be used in this context because it may not be passed or returned by reference

Reason for the Error & Solution

An expression cannot be used in this context because it may not be passed or returned by reference

Example

The following sample generates CS8156:

// CS8156.cs (7,27)

class Test
{
    delegate ref int D1();

    void Test1()
    {
        D1 d1 = () => ref 2 + 2;
    }
}

To correct this error

When not using referenceable variables, refactoring to return by value corrects this error:

class Test
{
    delegate int D1();

    void Test1()
    {
        D1 d1 = () => 2 + 2;
    }
}

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...