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

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