J. Chang J. Chang - 11 months ago 77
Vb.net Question

Why base classes must have default new?

I got this error

https://docs.microsoft.com/en-us/dotnet/visual-basic/misc/bc30387

And I wonder why.

What about if I never want to call parameterless new in both base and derived classes?

I can do that if I don't use inheritance. Why using inheritance means I can no longer do so?

To repeat the issue

What's the explanation? So NOT every classes need parameterless new but classes with inheritance must? That doesn't make sense.

What about if I never call derived class with parameter less constructor. I don't intent for the class to ever be constructed without parameter.

For example, say, I want to create a class without parameterless constructor. I can do that right.

But say I want to split the class into two. Parent and child class. I want BOTH not to ever have parameterless constructor.

It seems that I can't do that can I? If such is the case, can anyone please confirm it.

Answer Source

The link says that if you have an explicit constructor in your base class with parameters and no parameterless one than you cannot leave your derived class without constructor. Because VB.NET cannot create an implicit constructor for derived class.

If you don't write any constructors for both, it is perfectly valid.

public class Base

End Class

Public Class Derived 
    Inherits Base

End Class

However you cannot declare a derived class without an explicit constructor like below. Because VB.NET cannot determine how to initialize base class.

public class Base
    Public sub New(ByVal Item As Integer)

    End Sub
End Class

Public Class Derived 
    Inherits Base

End Class

To overcome this issue you can declare a default constructor on derived class which calls base class constructor with a default value.

public class Base
    Public sub New(ByVal Item As Integer)

    End Sub
End Class

Public Class Derived 
    Inherits Base

    Public Sub New()
        MyBase.New(5)

    End Sub
End Class
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download