Reflection, creating object with inherited cunstructor, how?

S

Søren M. Olesen

Hi

How do I create an instance of an object with an inherited cunstructor??

In the below example, I'm able to create an instance of MyClass2 using the
forst two lines of code, however if I try using the next two lines of code
it fails.



How do I create an instance of an object with an inherited cunstructor that
takes an argument??


TIA

Søren

Imports System.Reflection
Module Module1
Public Class MyBaseClass
Public Sub New()

End Sub
Public Sub New(ByVal arg As Boolean)

End Sub
End Class

Public Class MyClass2
Inherits MyBaseClass

End Class

Sub Main()

Dim conInfo As ConstructorInfo = GetType(MyClass2).GetConstructor(New Type()
{})
Dim myObj As Object = conInfo.Invoke(New Object() {})

Dim conInfo1 As ConstructorInfo = GetType(MyClass2).GetConstructor(New
Type() {GetType(Boolean)})
Dim myObj1 As Object = conInfo.Invoke(New Object() {False})
End Sub

End Module
 
P

Phill W.

Søren M. Olesen said:
How do I create an instance of an object with an inherited cunstructor that
takes an argument??

Constructors are *not* inherited.

What you are seeing is the /implicit/ creation (by the VB compiler) of a
niladic Constructor in the derived class because /you/ haven't coded
/any/ Constructors of your own in that class.
The code that's running is more like:

Module Module1
Public Class MyBaseClass
Public Sub New()
Public Sub New(ByVal arg As Boolean)

Public Class MyClass2
Inherits MyBaseClass
Public Sub New() <--- this one is written for you.

The /only/ way to call the constructors in the base class is to do so
from a duplicate constructor in the derived class, as in

Public Class MyClass2
Inherits MyBaseClass
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal arg As Boolean)
MyBase.New(arg)
End Sub
End Class

HTH,
Phill W.
 
S

Søren M. Olesen

Hmmm... I see, but how come that the new constructor on my baseclass gets
callen in the first example then??

Guess it must be more like:

Public Class MyClass2
Inherits MyBaseClass
Public Sub New()
MyBase.New()
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top