• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 426
  • Last Modified:

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
0
glenn_r
Asked:
glenn_r
  • 2
  • 2
1 Solution
 
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

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now