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.