Saturday 10 December 2016

Private Constructor In C#

Private Constructor :

There are following important points about private constructor

A ) Private constructor can not be inherited

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
    public class myClass
    {
        private myClass()
        {

        }
       
    }
    public class myClass1:myClass
    {
        private myClass1()
        {

        }
    }

}


Out Put:

Severity
Code
Description
Project
File
Line
Error
CS0122
'myClass.myClass()' is inaccessible due to its protection level
WebApplication1
D:\SandeepAllPractise\WebApplication1\WebApplication1\WebForm1.aspx.cs
26


















B )  we can not create a object of the class which has private constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            // myClass obj = new myClass();
            string str = myClass.myData();
        }
    }
    public class myClass
    {
        private myClass()
        {

        }
        public static string myData()
        {
            return "HI";
        }
    }
    public class myClass1:myClass
    {
        private myClass1()
        {

        }
    }
}



















* Some times we do not want to create instances of certain classes
 like utility,common routine classes.

No comments:

Post a Comment