Passing Type to a method

atmosphere

Member
Joined
Jun 14, 2005
Messages
8
Programming Experience
5-10
hey

I want to pass a type to a method so that I can cast a variable using this type. I cant seem to get it to work. Could someone give me a simple example?
 
you can pass a variable of a type, but you cant pass the type itself

VB.NET:
'Module added to the project:
Structure MyVariableType
  Dim FirstName As String
  Dim LastName As String
  Dim Age As Integer
End Structure

'Form1:
Dim Employee As MyVariableType
With Employee
  .FirstName = "Bob"
  .LastName = "Smith"
  .Age = 32
End With

Call MyMethod (Employee)

'The method:
Private Sub MyMethod (Byval Emp As MyVariableType)
  With Emp
	If .FirstName = "Bob" Then....
	If .LastName = "Smith" Then....
	If .Age = ....
   End With
End Sub

both the form and the method are using that variable type (well it's not actually a type but you know)

hope that helps
 
You actually can pass a Type to a method, because Type is a class like anything else in .NET. Try this code:
VB.NET:
 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		Dim n As Integer = 100

		Me.CastObject(n, GetType(String))
	End Sub

	Private Sub CastObject(ByVal obj As Object, ByVal typ As Type)
		MessageBox.Show("Value = " & obj.ToString() & ", Type = " & obj.GetType().ToString())
		Dim o As Object = Convert.ChangeType(obj, typ)
		MessageBox.Show("Value = " & o.ToString() & ", Type = " & o.GetType().ToString())
	End Sub

Edit:
Obviously this would require some exception handling in case the conversion is not valid.
 
Back
Top