Skip to main content

Constructors in C# with Examples

Constructors in C# with Examples

Constructor is a method which is invoked automatically whenever an instance of class or struct (structure) is created.  The constructor will have the same name as the class or struct and it useful to initialize and set default values for the data members of the new object.

 

In case, if we create a class without having any constructor, then the compiler will automatically create a one default constructor for that class. So, there is always one constructor that will exist in every class.

 

class can contain more than one constructor with different types of arguments in C#, and the constructors will never return anything, so we don’t need to use any return type, not even void while defining the constructor method in the class.

 

Constructor Syntax in C#

As earlier discussed, the constructor is a method and it won’t contain any return type. If you want to create a constructor in C#, then you need to create a method with the same as the class name.

 The following code is the syntax of creating a constructor in C#.

         class Person

    {

        //Constructor

        public Person()

        {

            // initialization Codes here

        }

    }

 

From the above syntax, we created a class called “Person” and a method whose name is same as the class name. Here the method Person() will become a constructor of our class.

 

Types of Constructor in C#

 

We have a different type of constructors available in C#, these are;

a.     Default Constructor

b.     Parameterized Constructor

c.      Copy Constructor

d.     Static Constructor

e.      Private Constructor

 Let’s take a detail look at each of the above constructors with examples in C#.

a.       Default Constructor

This type of constructor is created without having any parameters, every instance of the class will be initialized without any parameter values.

 

The code below is an example of defining the default constructor in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        public string Name;

        public string Location;

        // Default Constructor

        public Person()

        {

            Name = "Musa Sule";

            Location = "Abuja";

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // The constructor will be called automatically once the                  instance of class created

            Person user = new Person();

            Console.WriteLine(user.Name);

            Console.WriteLine(user.Location);

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

 

If we run the program, we will get the below output

 

Musa Sule

Abuja

 

b.      Parameterized Constructor

 

If we create a constructor with at least one parameter, then we will call it a parameterized constructor and every instance of the class will be initialized with parameter values.

 

The code for defining the parameterized constructor in C# is as shown below.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        public string Name;

        public string Location;

        // Parameterized Constructor

        public Person(string name,string location)

        {

            //members initialiazation

            Name = name;

            Location = location;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // The constructor will be called automatically once the instance of class             created and two string values must be supplied

            Person user = new Person("Musa Sule Gadabs","Abuja");

            Console.WriteLine(user.Name);

            Console.WriteLine(user.Location);

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

 

The output of the above code is the same as the above example, that is

Musa Sule Gadabs

Abuja


Private Constructor

Private Constructor is a special instance constructor and it is useful in classes that contain only static members. If a class contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance for that particular class except nested classes.

 

Private Constructor Syntax

     class Person

    {

        //Private Constructor

        private Person()

        {

 

        }

    }

 

Example of Private Constructor

The below code shows an example of creating a private constructor in C# to prevent other classes to create an instance of a particular class.

 

using System;

 

namespace CsharpnaijaTutorial

{

    class Person

    {

        //Private Constructor

        private Person()

        {

            Console.WriteLine("I am Private Constructor");

        }

        public static string Name;

        public static string Location;

 

        public Person(string name, string location)

        {

            Name = name;

            Location = location;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // The following comment line will throw an error because constructor is inaccessible

            //Person person = new Person();

 

            // The constructor will be called automatically once the instance of class created

            Person person = new Person("Musa Sule", "Abuja");

            Console.WriteLine(Person.Name + ", " + Person.Location);

            Console.WriteLine();

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

 

In the above example, we are accessing class properties directly with the class name because those are static properties so it won’t allow you to access the instance name.

 

Static Constructor

 Static Constructor is useful to perform a particular action only once throughout the application. If we declare a constructor as static, then it will be invoked only once irrespective of the number of class instances and it will be called automatically before the first instance is created.

 

In C# the static constructor will not accept any access modifiers and parameters. In simple words, we can say it’s parameterless.

 

The following are the properties of static constructor in C#.

         Static constructor in C# won’t accept any parameters and access modifiers.

        The static constructor will be invoked automatically, whenever we create the first             instance of a class.

        The static constructor will be invoked by CLR so we don’t have a control on static         constructor execution order in C#.

        In C#, only one static constructor is allowed to be created.

C# Static Constructor Syntax

Following is the syntax of defining a static constructor in c# programming language.

 

class Person

{

    // Static Constructor

    static Person()

    {

        // Your Custom Code

    }

}

 

Static Constructor Example

The following is an example of creating a static constructor in C# programming language to invoke the particular action only once throughout the program.

 

using System;

 

namespace CsharpnaijaTutorial

{

    class Person

    {

        //Private Constructor

        static Person()

        {

            Console.WriteLine("I am Static Constructor");

        }

        // Default Constructor

        public Person()

        {

            Console.WriteLine("I am Default Constructor");

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // Both Static and Default constructors will invoke for first instance

            Person user = new Person();

            // Only Default constructor will invoke

            Person user1 = new Person();

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

 

 

Constructor Overloading

Constructor can be overloaded by creating another constructor with the same method name but with different parameters.

 

The following is an example of implementing a constructor overloading in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        public string Name;

        public string Location;

        public Person()

        {

            Name = "Musa Sule";

            Location = "Abuja";

        }

        // Parameterized Constructor

        public Person(string name,string location)

        {

            //members initialiazation

            Name = name;//"Musa Sule";

            Location = location; //"Abuja";

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            //Default Constructor will be called

            Person newPerson = new Person();

            // The constructor will be called automatically once the instance of class created

            Person person = new Person("Sakinat Musa Sule","Abuja");

            Console.WriteLine(person.Name + ", " + person.Location);

            Console.WriteLine(newPerson.Name + ", " + newPerson.Location);

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

 

The output of the above program will be as shown below

Sakinat Musa Sule, Abuja

Musa Sule, Abuja

 Constructor Chaining

Constructor Chaining is an approach to invoke one constructor from another constructor. To achieve constructor chaining we need to use this keyword after our constructor definition.

 

The following code shows an example of implementing a constructor chaining in C#.

 

using System;

namespace CsharpnaijaTutorial

{

    class Person

    {

        public string Name;

        public string Location;

        public Person()

        {

            Console.Write("Hi, ");

        }

        // Parameterized Constructor

        public Person(string message):this()

        {

            Console.Write(message);

        }

        public Person(string message, string name) : this("Welcome")

        {

            Console.Write(message + " " + name);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // The constructor will be called automatically once the instance of class created

            Person person = new Person(" to","Csharpnaija");

            Console.WriteLine();

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

 

The output of the above program is as shown below

Constructor_Chaining


 Thank you

 References

1.     Geeksfor Geeks

2.     Tutlane


Comments

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...