C# Error CS8171 – Cannot initialize a by-value variable with a reference

C# Error

CS8171 – Cannot initialize a by-value variable with a reference

Reason for the Error & Solution

Cannot initialize a by-value variable with a reference

Example

The following sample generates CS8171:

// CS8171.cs (8,13)

class Test
{
    void A()
    {
        int a = 123;
        ref int x = ref a;
        var y = ref x;
    }
}

Remember that var y = ref x is implicitly int y = ref x where int y is a by-value variable.

To correct this error

Removing the ref modifier from the right side of the assignment will correct this error:

class Test
{
    void A()
    {
        int a = 123;
        ref int x = ref a;
        var y = x;
    }
}

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