#286 – A Constructor is Called When an Instance of a Class Is Created

A constructor is a method that is called when a new instance of a class is created.  (Technically, this definition applies to instance constructors–I’ll cover static constructors later).

A constructor normally allows a class to initialize its data members, as part of the process of creating a new instance.

A constructor is defined by using the class’ name as the method name.  The simplest form of constructor, known as the default constructor, takes no parameters.

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

        // Constructor, called when we create a new Dog
        public Dog()
            // Set a default name
            Name = "Pooch";

The constructor in the above example is called when we create a new instance of a Dog, using the new operator.

            Dog someDog = new Dog();

            Console.WriteLine(someDog.Name);       // Pooch

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: