Constructors
in C# with Examples
In this article, I am going to discuss the different types
of Constructors in C# with examples. Please
read our previous article before proceeding to this article where we
discussed how to create class and objects in C# with examples. As part of this article, we are going to
discuss the following pointers in details with examples.
Hi Guys, Welcome in my online
tutorials.
In this online tutorial, I am going to explain
you the different types of Constructors in C# with multiple examples.
Before proceeding to this article, please read our previous
article where I have discussed how to
create class and objects in C#.
- What is a Constructor in C#?
- Rules to follow while creating
Constructors in C#.
- What a Constructor can have in C#?
- Can we define a method with the same
class name in C#?
- How many types of constructors are there
in C#.Net?
- What is Default Constructor in C#?
- When do we need to provide the
constructor explicitly?
- What is User-Defined Default Constructor
in C#?
- When should we define a parameterized
constructor in a class?
- What is a Parameterized Constructor in
C#?
- How many constructors can be defined in a
class in C#?
- What is Copy Constructor in C#?
- Understanding Static Constructor in C#.
- Can we initialize non-static data members
within a static constructor in C#?
- Is it possible to initialize static data
fields within a non-static constructor in C#?
- Can we initialize static data fields in
both static and non-static constructor?
- What is Private Constructor in C#?
- Understanding constructor overloading in
C#?
What is a Constructor in C#?
A Constructor is a special types of method of a class which
automatically executed whenever we create an instance (object) of that class.
Constructors are responsible for:
1. object initialization
2. Memory allocation in heap.
Remember: new keyword creates the object of that class.
Ex: Employee myEmployee= new Employee();
Remember:
- Constructor name must be same as the
class name.
- It returns nothing, so we cannot define
any return type even void in Constructors.
- Constructor doesnot contain modifiers.
- As part of the constructor body return statement
with value is not allowed.
What is the work of Constructor in C#?
- Constructor allow all five accessibility
modifier.
- Constructor may or may not parameters.
- We can throw an exception from the
constructor if required.
Syntax:
Class Employee
{
Employee
()//Default Constructor
{
//
All logical statements allow here except return statement with value.
}
}
Example: Program to show the use of the
constructor in C#.
namespace ConstructorDemo
{
class Employee
{
Employee ()//Default Constructors
{
Console.WriteLine("This
is Default Constructor");
Console.ReadKey();
}
public static void Main(string[] args)
{
Employee p = new Employee ();
}
}
}
OUTPUT:
This is Default Constructor
Can we define a method with the same
class name in C#?
No, it is not possible to define a method with the same class name
in C#.
We receive a compile-time error if we do so.
How many types of constructors are
there in C#.net?
Basically 5 types of constructor are used in C#:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
- Static Constructor
- Private Constructor
Let’s discuss one by with examples.
Default Constructor in C#:
This constructor has no any parameter. Again we classified it into
two types:
- System-defined
- User-defined
What is System Defined Default
Constructor in C#?
If we are not defined any constructor explicitly in your program,
then the system will provide one by default constructor at the time of
compilation. That constructor is called a default constructor. This constructor
will assign default values to the data members (non-static variables). Because
it is created by the system so it is called system-defined default constructor.
Ex:
namespace MyConstructorDemo
{
class Employee
{
int id{get; set;}
string
name{get; set;}
int
age{get; set;}
string
address{get; set;}
public void
GetDetails()
{
Console.WriteLine("Employee
id is: " + id);
Console.WriteLine("Employee
name is: " + this.name);
Console.WriteLine("Employee
age is: " + this.age);
Console.WriteLine("Employee
address is: " + address);
}
}
class TestData
{
static void
Main(string[] args)
{
Employee
myEmployee1 = new Employee();
Employee
myEmployee2 = new Employee();
myEmployee1.GetDetails ();
myEmployee2.GetDetails ();
Console.ReadKey();
}
}
}
Output:
Employee id is: 0
Employee name is:
Employee age is: 0
Employee address is:
Employee id is: 0
Employee name is:
Employee age is: 0
Employee address is:
Remember: If you are not defined any constructor explicitly, system
will provide you a default Constructor.
When do we need to provide the
constructor explicitly?
At the time of object creation, if we want to execute some logic,
then we must provide the constructor explicitly.
What is User-Defined Default
Constructor in C#?
This constructor is defined by the user without any parameter. It
does not accept any parameter.
Syntax:
Class Employee
{
Employee
()//User defined Default Constructor
{
//
All logical statements allow here except return statement with value.
}
}
Ex:
namespace ConstructorDemo
{
class Employee
{
int id{get; set;}
string
name{get; set;}
int
age{get; set;}
string
address{get; set;}
public Employee()
{
this.id = 1001;
age
= 25;
this.name = " Allen
Donald";
address
= "Melbourne, Australia";
}
public void
GetDetails()
{
Console.WriteLine("employee
id is: " + id);
Console.WriteLine("employee
name is: " + this.name);
Console.WriteLine("employee
age is: " + this.age);
Console.WriteLine("employee
address is: " + address);
}
}
class Test
{
public static void Main(string[] args)
{
Employee
myEmployee1 = new Employee();
Employee
myEmployee2 = new Employee();
myEmployee1. GetDetails();
myEmployee2. GetDetails();
Console.ReadKey();
}
}
}
OUTPUT:
employee id is: 1001
employee name is: Allen Donald
employee age is: 25
employee address is:
Melbourne, Australia
employee id is: 1001
employee name is: Allen Donald
employee age is: 25
employee address is: Melbourne, Australia
Remember: Every object (myEmployee1 and myEmployee2) will be initialized with same values. It means it is not possible to initialize each object with
different values.
When should we define a parameterized
constructor in a class?
In previous example we have seen that it is not possible to
initialize each object with different values.
If you want to initialize each object dynamically with unique
values then we have to use the parameterized constructor.
Main advantage of parameterized constructor is: you can initialize
each object with unique values.
What is Parameterized Constructor in
C#?
Parametrized constructor allows us to provide parameters in
constructor in C#.
Parametrized constructor allows us to provide unique values for
each instance of the class.
Example of parameterized
constructor in C#:
namespace ParameterizedConstructorDemo
{
class Employee
{
int id { get; set; }
string name { get; set; }
int age { get; set; }
string address { get; set; }
public Employee(int id, string
name, int age, string address)
{
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public void
DisplayData()
{
Console.WriteLine("employee
id is: " + id);
Console.WriteLine("employee
name is: " + this.name);
Console.WriteLine("employee
age is: " + this.age);
Console.WriteLine("employee
address is: " + address);
}
}
class TestDemo
{
static void
Main(string[] args)
{
Employee
myEmployee1 = new Employee(1001, " Allen
Donald
", 25," Melbourne,
Australia");
Employee
myEmployee2 = new Employee(1002, "Donald
Trump",27, " Melbourne,
Australia");
myEmployee1. DisplayData ();
myEmployee2. DisplayData ();
Console.ReadKey();
}
}
}
OUTPUT:
employee id is: 1001
employee name is: Allen Donald
employee age is: 25
employee address is: Melbourne, Australia
employee id is: 1002
employee name is: Donald Trump
employee age is: 27
employee address is: Melbourne, Australia
How many constructors can be defined
in a class in C#?
We can define multiple numbers of constructors with different
signature in c#. Different signature means the number of parameters, type
of parameters and order of parameters should be different.
What is Copy Constructor in C#?
When we pass the parameter as class type in a constructor, then it
is called copy constructor. Copy constructor is used to copy one object data
into another object.
Purpose of the copy constructor: initialize a new object with
values of an existing object.
Example of copy constructor in
C#:
namespace CopyConstructorDemo
{
class Employee
{
int id { get; set; }
string name { get; set; }
int age { get; set; }
string address { get; set; }
public Employee()
{
Console.WriteLine("ENTER
EMPLOYEE DETAILS");
Console.WriteLine("Enter the
employee id");
this.id =
int.Parse(Console.ReadLine());
Console.WriteLine("Enter the
employee name");
this.name = Console.ReadLine();
Console.WriteLine("Enter the
employee age");
this.age = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the
employee address:");
this.address = Console.ReadLine();
}
public Employee(Employee myobj)
{
this.id = myobj.id;
this.name = myobj.name;
this.age = myobj.age;
this.address = myobj.address;
}
public void DisplayData()
{
Console.WriteLine();
Console.WriteLine("Employee id
is: " + this.id);
Console.WriteLine("Employee
name is: " + this.name);
Console.WriteLine("Employee
age is: " + this.age);
Console.WriteLine("Employee
address is: " + this.address);
}
}
class TestData
{
static void Main(string[] args)
{
Employee myEmployee1 = new
Employee();
Employee myEmployee2 = new
Employee(myEmployee1);
myEmployee1.DisplayData();
myEmployee2.DisplayData();
Console.ReadKey();
}
}
}
OUTPUT:
ENTER
DETAILS
Enter the
id
1001
Enter the
name
Donald Trump
Enter the
age
55
Enter the
address:
Melbourne, Australia
Id is: 1001
Name is: Donald Trump
Age is: 55
Address is: Melbourne, Australia
Id is: 1001
Name is: Donald Trump
Age is: 55
Address is: Melbourne, Australia
Understanding Static Constructor in
C#:
Like other Constructor, we can also create Static Constructor. Static Constructor is invoked only once when
creating first instance (object) of the class.
Static Constructor is used to initialize the static fields of
the class. If we write some code inside the static constructor, it will execute
only once, when creating first instance (object) of the class.
Remember:
- We can define only one static constructor
in a class.
- Static constructor has no any parameter.
- Static constructor access static members
of the class.
- No any access modifier define in static
constructor definition.
- We cannot create the object for the
static class.
- Static constructor invoked only once. It
is called at the time of first object creation of the class. After that
any object creation static constructor will not be called.
Ex: Static Constructor
with an example:
namespace ConstructorDemo
{
class StaticconstructorDemo
{
int i;
static int j;
public StaticconstructorDemo()
{
i = 100;
}
static StaticconstructorDemo()
{
j = 100;
}
public void Display()
{
Console.WriteLine("value of i :
" + i);
i++;
Console.WriteLine("value of j
: " + j);
j++;
}
}
class TestDemo
{
static void Main(string[] args)
{
StaticconstructorDemo myDemo1 = new
StaticconstructorDemo();
e1.Display();
e1.Display();
StaticconstructorDemo myDemo2 = new
StaticconstructorDemo();
myDemo1.Display();
myDemo2.Display();
Console.ReadKey();
}
}
}
OUTPUT:
value of i : 100
value of j : 100
value of i : 101
value of j : 101
value of i : 100
value of j : 102
value of i : 101
value of j : 103
Is it possible to initialize
non-static data members within a static constructor in C#?
No it is not possible. If we do show, we will get compile time
error.
Ex:
namespace OOPSDEMO
{
class StaticconstructorDemo
{
int i;
static int j;
static StaticconstructorDemo()
{
i=101; //not allowed
j=100;
}
}
class TestDemo
{
static void Main(string[] args)
{
Console.ReadKey();
}
}
}
Output: An object reference is
required for the non-static field, method, or property.
Can we initialize static data fields
within a non-static constructor in C#?
Yes it is possible. Consider the following example:
namespace OOPSDEMO
{
class
NonStaticconstructorDemo
{
public int
i;
public
static int j;
public NonStaticconstructorDemo()
{
i=100;
j=101;
}
}
class TestDemo
{
static void
Main(string[] args)
{
NonStaticconstructorDemo myDemo1 = new NonStaticconstructorDemo();
Console.WriteLine("value of i : " + myDemo1.i);
Console.WriteLine("value of j : " +
NonStaticconstructorDemo.j);
Console.ReadKey();
}
}
}
Output:
value of i : 100
value of j : 101
Can we initialize static data fields
in both static and non-static constructor?
Yes, it is possible.
What is Private Constructor in
C#?
A constructor whose accessibility is private is called Private constructor. We cannot create an
object for Private constructor outside of the class. Private constructor is
used to create an object within the same class. Generally, private constructors
are used in Remoting concept.
Example of private constructor:
namespace PrivateConstructorDemo
{
class PCDemo
{
private PCDemo ()
{
Console.WriteLine("This
is private constructor demo.");
}
static void
Main(string[] args)
{
PCDemo
myPCDemo = new PCDemo ();
Console.ReadKey();
}
}
}
Output: This is private constructor
demo.
What is constructor
overloading?
Constructor
overloading means multiple constructors within a class with different parameter
types, different number of parameters and different order of parameters.
Example of Constructor Overloading in C#:
namespace ConstructorOverloadingDemo
{
public
class MyConstructorOverloading
{
int
myValue;
public
MyConstructorOverloading()
{
this.myValue = 10;
}
public
MyConstructorOverloading(int x)
{
this.myValue = x;
}
public
void DisplayData()
{
Console.WriteLine("the value of myValue:{0}", myValue);
}
}
class
TestDeta
{
static
void Main(string[] args)
{
MyConstructorOverloading myObj1 = new MyConstructorOverloading();
MyConstructorOverloading myObj2 = new MyConstructorOverloading(50);
myObj1.DisplayData();
myObj2.DisplayData();
Console.ReadKey();
}
}
}
OUTPUT:
the value of myValue:10
the value of myValue:50
That’s it for today. In the next article, I am going to discuss
the Destructors
in C# with examples. Here, in this article, I try to explain
the different types of Constructors in C# with examples. I hope now you understood the need and use of
different types of constructors.
0 comments:
Post a Comment