Reputation: 94429
I am having trouble understanding the rules for how the short hand syntax works for object initializers in C#. I see some evidence that I can use a shorthand syntax to declare a property and value using a local variable to handle both the property and its value. I should note the documentation does not make any references to this syntax that I could find in relationship to object initializers.
Here is an example:
string Title = "Test";
var obj = new
{
Title
};
This works as I would expect and similar to how JavaScript handles the situation. When I attempt to use this syntax with an object that is not anonymous it produces a compile error.
Here is an example:
Book book = new Book
{
Title = "Hit Refresh"
};
Book anotherBook = new Book
{
book.Title //CS1922: Collection initializer requires its type 'type' to implement System.Collections.IEnumerable.
};
class Book
{
public string Title { get; set; }
}
Can anyone explain why the first example works, but the second does not? I cannot find any information in the C# documentation that explains this issue.
Upvotes: 3
Views: 1738
Reputation: 1499880
Can anyone explain why the first example works, but the second does not?
Basically because that's the way the language is designed. Anonymous object creation expressions support projection initializers (the feature you're describing) whereas normal object initializers don't.
I think this is reasonable: when you're creating an instance of an anonymous type, that code is in control of both the property names and values. When you're creating an instance of a regular type, you don't get to choose the property names - only the values. That makes it odd for the expression used to select the value to also select the property name.
Additionally, the syntax of just passing values is already in use - for collection initializers. For example:
var titles = new List<string> { book.Title };
That's why you're getting error CS1922 - you're using valid syntax, but it's to implement a different features. There's no conflict for anonymous types, because they're not collections.
I personally don't think it's a big deal to write:
Book anotherBook = new Book { Title = book.Title };
Or in C# 10 you can use:
Book anotherBook = new { Title = book.Title };
Upvotes: 5