VB.NET create method parameter of type

Is it possible to pass in a type reference where the members of the method could create an object of the specified type?

Example:

sub sample(myclassname)

   dim obj1 as new myclassname

   obj.name="somename"
   obj.height ="100"

   dim obj2 as new myclassname

   obj.name="someothername"
   obj.height ="200"

end sub
glenn_rAsked:
Who is Participating?
 
MlandaTCommented:
Or maybe you have a type name and you want to create an object of that type. You can also look at Activator.CreateInstance or Assembly.CreateInstance:
Function Sample(ByVal MyClassName as String) As Object

    Dim item As Object = Activator.CreateInstance(Type.GetType( MyClassName ))
    Return item

End Function

Open in new window

0
 
glenn_rAuthor Commented:
In the calling method how do I get the name of the class to pass in? Creating a new instance works '(new class).name' but is there some way to get the name without creating a new instance?

sub callsample()
    Sample((new myclass).name)
end sub

Function Sample(ByVal MyClassName as String) As Object

    Dim item As Object = Activator.CreateInstance(Type.GetType( MyClassName ))
    Return item

End Function
0
 
MlandaTCommented:
The assumption made with the CreateInstance is that you already have the fully qualified type name. These might shed more light:

http://www.knowdotnet.com/articles/activator_createinstance.html
http://stackoverflow.com/questions/3432317/visual-basic-dynamically-create-objects-using-a-string-as-the-name
0
 
glenn_rAuthor Commented:
This works

GetType(MyClass).tostring or just pass in the type
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.