#703 – Object Initializers Allow Setting Either Fields or Properties

When you use an object initializer, you can specify the value that one or more of the object’s properties should take on, after the object is constructed.

Dog d = new Dog { Name = "Bowzer", Age = 2 };

If your class includes public fields, you can also initialize the fields within the object initializer.

For example:

    public class Dog
    {
        // Properties
        public string Name { get; set; }
        public int Age { get; set; }

        // Field
        public double CollarSize;

        // Constructors
        public Dog()
        {
        }
    }
            Dog d2 = new Dog { Name = "Kirby", Age = 15, CollarSize = 12.2 };
Advertisement