views:

51

answers:

2

I have a "MustInherit" .NET class which declares a constructor with an integer parameter. However, Visual Studio gives me an error when I create any derived class stating that there is no constructor that can be called without any arguments. Is it possible to inherit the constructor with arguments?

Right now, I have to use

Public Sub New(ByVal A As Integer)
    MyBase.New(A)
End Sub

in the derived classes. Is there any way to avoid this?

+2  A: 

No, this is not possible. Every constructor that has arguments in the base class must be redeclared in the derived class.

Darin Dimitrov
@"Darin Dimitrov" - not strictly correct. Please see http://stackoverflow.com/questions/2550747/how-to-inherit-constructors-with-arguments-in-net/2550895#2550895.
Enigmativity
A: 

Yes, this is possible. But you must call the base constructor with an integer.

public class A
{
    public A(int x)
    {
    }
}

public class B : A
{
    public B()
        : base(42)
    {
    }
}

or

Public Class B
    Inherits A

    Public Sub New()
        MyBase.New(42)
    End Sub
End Class
Enigmativity
This isn't inheritance of the constructor - class B doesn't have a constructor accepting an integer.
M.A. Hanin
@"M.A. Hanin" - I don't think that the question is about inheriting the constructor, but inheriting a class without a parameterless constructor resulting in a derived class with a parameterless constructor. Otherwise the question really wouldn't make sense.
Enigmativity
Actually, the question _is_ about inheriting the constructor. Since the variables being initialized are all declared by the base class, I wanted the base class constructor to be used. That is, the constructor would not be changed by any derived classes. But apparently this seems impossible.
Soumya92
@Soumya91 - I want to clarify what is going on here. You can't inherit a constructor - you can only inherit classes. You can chain a constructor by calling the base constructor. We are chaining constructors, not inheriting them. So, do you want the derived constructors to also have the integer parameter or not? I read your question as you do not and my solution covers that. Please let me know what you meant if I go it wrong. If I'm right please up-vote. :-)
Enigmativity