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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...