- Back to Home »
- C#.NET »
- C#.NET Constructor - with parameter, overloading
Posted by :
Sudhir Chekuri
Tuesday, 5 January 2016
- Constructor is a special method which has the same name of the class.
- It is invoked automatically when an object for that class is created.
- It is used for initializing the components of a class.
Program
using System;
namespace constructor
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Console.ReadKey();
}
public Program()
{
Console.WriteLine("program");
}
}
}
program
In the above example a constructor with name Program is declared i.e., with the same name of the class in which it is declared.
This constructed is invoked automatically when an object is created for the Program class.
So, When an object p is created for the class Program constructor is invoked and the code inside that gets executed to print program on the output screen
Constructor with parameter
Declaring a user defined constructor with and input parameter is known as Constructor with parameter or parameterized constructor.Example program to declare a parameterized constructor for a class
Program
using System;
namespace constructor
{
class Program
{
static void Main(string[] args)
{
Program p = new Program(5);
Console.ReadKey();
}
public Program(int i)
{
Console.WriteLine("Parameter value: "+i);
}
}
}
Output
Parameter value: 5
Constructor Overloading
Multiple constructors for the same class with the same names but different parameters is known as constructor overloading.Example program for constructor overloading
using System;
namespace constructor
{
class Program
{
static void Main(string[] args)
{
Program p = new Program(5);
Program p1 = new Program(5, 10);
Console.ReadKey();
}
public Program(int a)
{
Console.WriteLine("Parameter value: " + a);
}
public Program(int a, int b)
{
Console.WriteLine("Sum: " + (a + b));
}
}
}
Output
Parameter value: 5
Sum: 15