Constructor
Constructors are special methods called when a class is instantiated.
- Constructor will not return anything.
- Constructor name is same as class name.
- By default C# will create default constructor internally.
- Constructor with no arguments and no body is called default constructor.
- Constructor with arguments is called parameterized constructor.
- Constructor by default public.
- We can create private constructors.
- A method with same name as class name is called constructor there is no separate keyword.
Sample Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BRK.ConstructorExample
{
class Welcome
{
// Default constructor
public Welcome()
{
Console.WriteLine("Welcome message from Default Constructor...");
}
// Parametarized constructor
public Welcome(string name)
{
Console.WriteLine("\n\nThis message from parametarized constructor");
Console.WriteLine("Welcome to Constructor sample, by {0}", name);
}
}
class Program
{
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default constructor
Welcome obj = new Welcome();
// Creating object for welcome class by passing parameter
// This will called parametarized constructor which matches
Welcome pObj = new Welcome("Ramakrishna Basgalla");
Console.Read();
}
}
}
Output

Private Constructor
As I mentioned above we can create private constructors, but we have limitation in using that. The following program shows how to create and use a private constructor.
Sample Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BRK.PrivateConstructorSample
{
class Welcome
{
// Default private constructor
private Welcome()
{
Console.WriteLine("Welcome message from Default Private Constructor...");
Console.WriteLine("Created by Ramakrishna Basagalla (-:");
}
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default private constructor
Welcome obj = new Welcome();
Console.Read();
}
}
}
Output



Abhishek JaiswalPosted Jul 2, 2014, 1:08 AM
Nicely Explained!
Sam HobbsPosted Jan 20, 2012, 3:38 PM
Destructors are usually not needed, correct? I think the first thing that should be said about Destructors is that they are usually not needed. The most common use of destructors is to do cleanup of unmanaged objects.
Vineet Kumar SainiPosted Nov 26, 2011, 5:42 AM
Very useful for beginner student.......
Vineet Kumar SainiPosted Nov 26, 2011, 5:42 AM
Very useful for beginner student.......
ashish fPosted Jan 10, 2011, 12:03 AM
Can we override constructor???
Vijay GillPosted Dec 10, 2010, 8:06 AM
this is a test Another line