Object Initializers, Collection Initializers, and Projection Initializers were introduced in C# 3. I use Object and Collection Initializers all the time, but I constantly forget about the shortcut for creating and assigning properties of anonymous types using Projection Initializers.
Projection Initializers
Per the C# documentation, projection initializers are a shorthand for a declaration of and assignment to a property with the same name.
This is nothing but a shortcut way to create and assign properties on an anonymous type when copying values from a property on another type with the same property name. That is probably clear as mud, but below is an example of creating an anonymous type using a projection initializer.
class Program
{
static void Main(string[] args)
{
var contact = new Contact {
Id = 1,
Firstname = "John",
Lastname = "Doe",
Email = "john.doe@gmail.com"
};
// Using a Projection Initializer
var contactDetails = new {
contact.Id,
Name = contact.Firstname + " " + contact.Lastname,
contact.Email
};
Console.WriteLine(contactDetails);
Console.ReadLine();
}
}
public class Contact
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
}
Notice when I create contactDetails I don't specify a property name when assigning contact.Id and contact.Email. C# will take that to mean that my anonymous type should use the property names of Id and Email just like on the Contact Type. Creating an anonymous type using this shortcut is referred to as using a Projection Initializer.
Displaying the anonymous type on the Console will verify that indeed the new anonymous type does use the Id and Email properties:

I realize this isn't anything revolutionary, but I typically forget about this little shortcut and use the full object initializer method which can get a bit verbose when assigning a lot of values.
Hope this helps.

Comments