C# Error CS1917 – Members of readonly field ‘{0}’ of type ‘{1}’ cannot be assigned with an object initializer because it is of a value type

C# Error

CS1917 – Members of readonly field ‘{0}’ of type ‘{1}’ cannot be assigned with an object initializer because it is of a value type

Reason for the Error & Solution

Members of read-only field ‘name’ of type ‘struct name’ cannot be assigned with an object initializer because it is of a value type.

Read-only fields that are value types can only be assigned in a constructor.

To correct this error

  • Change the struct to a class type.

  • Initialize the struct with a constructor.

Example

The following code generates CS1917:

// cs1917.cs  
class CS1917  
{  
    public struct TestStruct  
    {  
        public int i;  
    }  
    public class C  
    {  
        public readonly TestStruct str = new TestStruct();  
        public static int Main()  
        {  
            C c = new C { str = { i = 1 } }; // CS1917  
            return 0;  
        }  
    }  
}  

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