What is Constructors?
Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.
Here you need to remember that a class can have any number of constructors and constructors don’t have any return type, not even void and within a class we can create only one static constructor.
Generally constructor name should be same as class name. If we want to create constructor in a class we need to create a constructor method name same as class name check below sample method for constructor
Sample code of Constructors:
class Example
{
public Example()
{
Console.WriteLine("Sample code of Test Method");
}
}
{
public Example()
{
Console.WriteLine("Sample code of Test Method");
}
}
Types of Constructors
Basically constructors are 5 types those are
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
Default Constructor
A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below
using System;
namespace ConsoleApplication1
{
class Sample
{
public string s, s1;
public Sample() // Default Constructor
{
s = "Welcome";
s1 = "ASP TANMOY";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically constructor will be called
Console.WriteLine(obj.s);
Console.WriteLine(obj.s1);
Console.ReadLine();
}
}
}
namespace ConsoleApplication1
{
class Sample
{
public string s, s1;
public Sample() // Default Constructor
{
s = "Welcome";
s1 = "ASP TANMOY";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically constructor will be called
Console.WriteLine(obj.s);
Console.WriteLine(obj.s1);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below
Wlcome
ASP TANMOY
ASP TANMOY
No comments:
Post a Comment