Compiler Error CS1914
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
- 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
}
}
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for