C# Error CS1914 – Static field or property ‘{0}’ cannot be assigned in an object initializer

C# Error

CS1914 – Static field or property ‘{0}’ cannot be assigned in an object initializer

Reason for the Error & Solution

Static field ‘name’ cannot be assigned in an object initializer

Object initializers by definition initialize objects, or instances, of classes. They cannot be used to initialize a static field of a type. No matter how many instances of a class are created, there is only one copy of a static field.

To correct this error

  1. Either change the field to an instance field in the type, or remove the attempt to initialize it from the object initializer.

Example

The following code generates CS1914 because the initializer tries to initialize the TestClass.Number field, which is static:

// cs1914.cs  
using System.Linq;  
public class TestClass  
{  
    public string Message { get; set; }  
    public static int Number { get; set; }
}  
class Test  
{  
    static void Main()  
    {  
        TestClass b = new TestClass() { Message = "Hello", Number = "555-1212" }; // CS1914  
  
    }  
}  

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