Jay
Jay

Reputation: 27464

In VB, is there a way to create an instance of the current type without naming it?

I mean, I want to say something like:

class Fwacbar
  public function MakeOne() as MyClass
    return new MyClass()
  end function
end class

Using MyClass doesn't work, but I mean, being I'm within class Fwacbar, I want to return an instance of Fwacbar.

Okay, I could just say "new Fwacbar". My goal is that I have a bunch of similar classes and I want to be able to cut and paste and have to make minimal changes. It would be nice if I didn't have to change all the "new"s. It's not essential to be able to do this to write the program, but I was just thinking about it and if I knew a way to do it, maybe it would be more valuable elsewhere.

Upvotes: 1

Views: 52

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39122

It's definitely an odd request...but here you go:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim f1 As New Fwacbar
        Dim f2 = f1.MakeOne
        Debug.Print("f1: " + f1.GetType.ToString)
        Debug.Print("f2: " + f2.GetType.ToString)
    End Sub

    Public Class Fwacbar

        Public Function MakeOne() As Object
            Return Me.GetType.GetConstructor(New System.Type() {}).Invoke(Nothing)
        End Function

    End Class

End Class

Upvotes: 2

Related Questions