Converting Objects To Type

adriaan

Member
Joined
Feb 28, 2005
Messages
13
Programming Experience
5-10
Hi,

I am trying to convert a type into a certain object, eg:

Public Function LoadObject(ByVal objType As Type) As Object

Dim oObj As Object = New Object
'convert oObt to objType---> how
DoSomething(oObj)
End Function

DoSomething Method needs the object to be a object as objType how to convert it?

thanks
 
Well this is how you convert one thing from another
For instance this is how you convert an interget into a string
VB.NET:
Dim i as Integer = 2
Console.write(CType(i,String))
 
Well, you could use two keywords to convert types in .NET; CType and DirectCast.
The difference between these two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. DirectCast throws an InvalidCastException error if the argument types do not match.

Cheers ;)
 
I was a bit in a hurry to ask the question, what I actually wanted to do was to create a intance of the passed on type. But I did find the answer:

VB.NET:
Public Function GetList(Byval objType As Type) As Object()
  
	Dim obj As Object
	
	obj = Activator.CreateInstance(objType)
	DoSomething(obj)
 
End Function

Thanks for the replies.
 
Back
Top