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

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