HomeCSharpC# Error CS1918 – Members of property ‘{0}’ of type ‘{1}’ cannot be assigned with an object initializer because it is of a value type

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

C# Error

CS1918 – Members of property ‘{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 property ‘name’ of type ‘type’ cannot be assigned with an object initializer because it is of a value type.

This error occurs when you try to use an object initializer to initialize the properties of a struct type that is itself a property of the class that is being initialized.

To correct this error

  1. If you must fully initialize the fields of the property in the object initializer, change the struct to a class type. Otherwise, initialize the struct members in a separate method call after you create the object by using the object initializer.

Example

The following example generates CS1918:

// cs1918.cs  
public struct MyStruct  
{  
    public int i;  
  
}  
public class Test  
{  
    private MyStruct str = new MyStruct();  
    public MyStruct Str  
    {  
        get  
        {  
            return str;  
        }  
    }  
    public static int Main()  
    {  
        Test t = new Test { Str = { i = 1 } }; // CS1918  
        return 0;  
    }  
}  

Leave a Reply

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