Prevent access of default constructor of base class in C#

Total Post:117

Points:821
C# 
C#
 1784  View(s)
Ratings:
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)
    {
    }
}
  1. Post:412

    Points:2888
    Re: Prevent access of default constructor of base class in C#

    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)
        {
        }
     }

      Modified On Apr-04-2018 04:38:38 AM
  1. Post:2

    Points:14
    Re: Prevent access of default constructor of base class in C#

    Depending on the context in which a member declaration takes place, only certain types of declared accessibility are permitted. Furthermore, when a member declaration does not include any access modifiers, the context in which the declaration takes place determines the default declared accessibility.

    top level class: internal 

    method: private

    members (unless an interface or enum): private (including nested classes)

    members (of interface or enum): public

    constructor: private (note that if no constructor is explicitly defined, a public default constructor will be automatically defined)

    delegate: internal

    interface: internal

    explicitly implemented interface member: public!

  1. Post:3

    Points:21
    Re: Prevent access of default constructor of base class in C#

    Post is removed by the Admin.

Answer