Home > DeveloperSection > Forums > Prevent access of default constructor of base class in C#
jayprakash sharma
jayprakash sharma

Total Post:117

Points:821
Posted on    March-26-2014 3:51 AM

 C# C# 
Ratings:


 1 Reply(s)
 971  View(s)
Rate this:

I have a base class and a derived class. As both the classes are serializable, it require to have default constructor. But I want to prevent access of default constructor of base class because it may cause a problem if someone will create object with default constructor. I cannot make it as private or internal as it is base class. Making it private shows error in derived class. The error is base does not have any parameter less constructor. How can I prevent access of default constructor of base class? Below is the sample code.

[Serializable]

public class Test1()

{

    public Test1()

   {

    }

    public Test1(int i, int j)

    {

    }

    public Test1(int i, int j, int k)

    {

    }

 }

[Serializable]

public class Test2():Test1

{

    public Test2():base()

    {

    }

    public Test2(int i, int j):base(i,j)

    {

    }

    public Test2(int i, int j, int k):base(i,j,k)

    {

    }

}



Pravesh Singh

Total Post:411

Points:2881
Posted on    March-26-2014 4:27 AM

Hi Jay,

Use protected .

The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances. For a comparison of protected with the other access modifiers.

public class Test1()

{

    protected Test1()

    {

    }

    public Test1(int i, int j)

    {

    }

    public Test1(int i, int j, int k)

    {

    }

 }


Don't want to miss updates? Please click the below button!

Follow MindStick