#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: