software master at the intersection of technology, science and art

home

download

object initializers


Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type, Cat. Note the use of auto-implemented properties in the Cat class.


Cat cat = new Cat { Age = 10, Name = "Fluffy" };


This technigue is used often in Linq in initializing a new anonymous type and is the only way to do such initializations.


Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable.


List digits = new List { 0 + 1, 12 % 3, MakeInt() };