Understanding Constructors (C#)

What is constructor?

Constructor is a special type of function member of a class. It is used to initialize the instance variables of the object.

Person myPerson=new Person();

Here the new operator is used to allocate the memory needed to store the data of the object.

Now suppose this is how we have defined our Person class.

  public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }  
   

( here we have used Automatic Properties feature of C# 3.0 to declare our properties FirstName and LastName)

Here in our class we haven’t defined a constructor but we are still able to create instance variables of the Person Object using following line of code

Person p = new Person();
 

The reason it is possible is because we don’t have to explicitly declare constructor for a class, C# automatically provides a default parameterless constructor for that class. The default constructor will initialize any fields of the class to their zero-equivalent values.

We can also write our own constructors, the things to remember are

  • They don’t have a return type.
  • Their name should be same as the name of the class.
  • Should contain a parameter list, which could be left empty.

Now the question is why would we be writing our own constructors?

Well the reason is because constructors can be used to pass initial values for an object’s fields at the time when an object is being instantiated.

For our above Person class

instead of the following code 

    Person p = new Person();
    p.FirstName = "Nishant";
    p.LastName = "Rana";

 

we can do the same in single line of code

Person p = new Person("Nishant", "Rana");
 

The constructor would be defined in the following manner

 public Person(string fname, string lname)
          {
              FirstName = fname;
              LastName = lname;
          }

One thing we have to remember is that if we are defining our own Parameterized constructor the default constructor would be eliminated.

We won’t be able to create person class object using default constructor.

i.e. Person p=new Person(); // it won’t compile.

In this case then we need to explicitly write a default constructor.

public Person()
        { 

        }

bye..


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

1 thought on “Understanding Constructors (C#)”

Share your thoughts

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 )

Google+ photo

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

Connecting to %s