C# Error CS8173 – The expression must be of type ‘{0}’ because it is being assigned by reference

C# Error

CS8173 – The expression must be of type ‘{0}’ because it is being assigned by reference

Reason for the Error & Solution

The expression must be of type because it is being assigned by reference

When assigning a reference to a variable, the type of the variables must match to be referenceable.

Example

The following sample generates CS8173:

// CS8173.cs (12,18)

class C
{
    void M()
    {
        string s = "s";
        object o = s;
        ref string rs = ref s;
        ref object ro = ref o;

        ro = ref s;
    }
}

To correct this error

Assigning the reference to a variable of the correct type will correct this error:

        rs = ref s;