Private Constructor
Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.
Example:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace DempApp
{
public class Sample
{
public string var1, var2;
public Sample(string a, string b)
{
var1 = a;
var2 = b;
}
private Sample() // Private Constructor Declaration
{
Console.WriteLine("Private
Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here
we don't have chance to create instace for private constructor
//
Sample obj = new Sample(); //Error
Sample obj1 = new Sample("Welcome", "to rpsingh");
Console.WriteLine(obj1.var1 + "
" + obj1.var2);
Console.ReadLine();
}
}
}
Note:-
In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.
Important points of private constructor
1. One use of private construct is when we have only static member.
2. Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
3. If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor
No comments:
Post a Comment