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.
A 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
{
//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
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
2.
Tutlane
Comments
Post a Comment