C# Error CS1648 – Members of readonly field ‘{0}’ cannot be modified (except in a constructor or a variable initializer)

C# Error

CS1648 – Members of readonly field ‘{0}’ cannot be modified (except in a constructor or a variable initializer)

Reason for the Error & Solution

Members of readonly field ‘identifier’ cannot be modified (except in a constructor or a variable initializer)

This error occurs when you attempt to modify a member of a field which is readonly where it is not allowed to be modified. To resolve this error, limit assignments to readonly fields to the constructor or variable initializer, or remove the readonly keyword from the declaration of the field.

Example

The following sample generates CS1648:

// CS1648.cs
public struct Inner
{
    public int i;
}

class Outer
{
    public readonly Inner inner = new Inner();
}

class D
{
    static void Main()
    {
        var outer = new Outer();
        outer.inner.i = 1;  // CS1648
    }
}

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