Microsoft Developer
Microsoft Developer

Reputation: 5459

Prevent access of default constructor of base class

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

    }
 }

Upvotes: 0

Views: 660

Answers (3)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

Go ahead and throw exception in Constructor as Serializer won't use it. If anybody uses he's the culprit :p

[Serializable]
public class Test1()
{
    public Test1()
    {
        throw new InvalidOperationException("Default constructor shouldn't be used")
    }

    public Test1(int i, int j)
    {

    }

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

    }
 }

Upvotes: 1

user1968030
user1968030

Reputation:

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

    }
 }

Upvotes: 1

tdelepine
tdelepine

Reputation: 2016

I searched several issue for this case. One solution to almost own it's to use obsolete anotaion with paramater to true for building fail.

...
    [Serializable]
    public class Test2():Test1
    {
        [Obsolete("Don't use the default constructor.", true)]
        public Test2():base()
        {

        }
...

Upvotes: 0

Related Questions