Thursday 16 June 2016

What will happen if we make constructor private in a class in c#?



Important Link :-

If we make the constructor private in the class using C#, then we can’t perform following thing as below:-

1.)  Restrict object creation of class: - if constructor of a class is private, then it is not available to outside of class. 

Example:-
 
namespace ConsoleApplication1
{
   
    public class car
    {
        private car();
       
    }
    class Program 
    {
        static void Main(string[] args)
        {
            car c = new car(); // car.car() is inaccessable due to its         protection level

        }
    }
}

2.)  No class can derive from it: - We know that when create object of derived class, base class constructor will called automatically first. As, base class constructor is private, it is not accessible to derived class and cannot be called from derived class. 

Example :- 
 
public class car
    {
        private car(){}

        public void GearSystem() { }
    }
    public class Maruti : car // car.car() is inaccessable due to its protection level
    {
   
    }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.