C# Class Constructors


This entry is part 2 of 8 in the series C# Classes Intermediate

What is a constructor? A constructor is a method called when an instance of a class is created. The intention here is put an object in an early state, meaning that we want to initialize some of the fields in our object. The constructor has the exact same name as the class. This is a requirement. Constructors, unlike other methods do not have a return type (not even void). In the constructor we can write any code we want that initializes.

Writing constructors is optional. If you don’t define a default constructor for your class, the C# compiler will create one for you. You will not see it in your code but it will be in the intermediate code. If you want to look at intermediate code, have a look at the post called C# ildasm.

An instance constructor is a special method that is executed whenever a new instance of a class is created. A constructor is used to initialize the state of the class instance. If you want to be able to create instances of your class from outside the class, you need to declare the constructor public. A constructor looks like the other methods in a class declaration, with the following exceptions:

  • The name of the constructor is the same as the name of the class.
  • A constructor cannot have a return type.

Constructors are like other methods in the following ways:

  • A constructor can have parameters. The syntax for the parameters is exactly the same as for other methods.
  • A constructor can be overloaded.
public class Customer
    {
        public Customer()
        {
        // a parameterless (default) constructor
        }
    }

This is from Mosh Hamedani’s video called “Constructors” from the Udemy.com course called C# Intermediate: Classes, Interfaces and OOP. You can use a constructor to initialize fields.

namespace Constructors1
{
    public class Customer
    {
        public string Name;  // in real world these are private
        public int Id;  // in real world these are private
        public Customer(string name)
        {
            // get the name of the Customer and set the 
            // Name property.
            this.Name = name;
            // "this" references the current object
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var customer = new Customer("Jack");

            Console.WriteLine(customer.Name);
            Console.ReadKey();
        }
    }
}

Here is the flow of the string”Jack”.

Series Navigation<< C# Classes IntermediateC# Class Constructor Overloading >>