Passing type as a parameter

  • Thread starter Thread starter Igor R.
  • Start date Start date
I

Igor R.

Hello,

I'd like to pass a type as a parameter to a function. For example:

void testTypeCast(Object o, Type t)
{
// of course, it doesn't compile
var casted = o as t;
}

and I'd like to call it like this:

testTypeCast(myObj, MyClass);

Is there a way to accomplish the above?

Thanks.
 
Igor R. said:
I'd like to pass a type as a parameter to a function. For example:

void testTypeCast(Object o, Type t)
{
// of course, it doesn't compile
var casted = o as t;
}

and I'd like to call it like this:

testTypeCast(myObj, MyClass);

Is there a way to accomplish the above?

No, not the way that you want it. The problem is not passing a Type
(which can be done precisely in the way you wrote). The "wrong" part is the
conversion itself. WHERE do you want to store the converted value? Well, you
want a variable of type t. But you can't declare a variable of that type
because it is not known at compile time (you wish to pass it as a
parameter). You also can`t use "var", because this one is also typed at
compiled time. So you need to declare a variable that can accept any type,
which limits you to "object" (or maybe "dynamic" if you are using C# 4.0).
So you need to do something like:

object casted = o as t;

The "o as t" part will not compile. But it is useless in general, since
you are going to store the result in an object anyway. So you might as well
do this:

object casted = o;

Of course, the "o as t" part does something else besides the cast: It
returns null if o is not t. System.Type has methods that let you compare the
type:

void testTypeCast(Object o, Type t)
{
object casted = null;
if (t.IsInstanceOfType(o))
casted = o;
}
 
I'd like to pass a type as a parameter to a function. For example:

void testTypeCast(Object o, Type t)
{
// of course, it doesn't compile
var casted = o as t;
}

and I'd like to call it like this:

testTypeCast(myObj, MyClass);

Is there a way to accomplish the above?

I am skeptical about its usefulness but try:

T testTypeCast<T>(Object o) where T : class
{
return o as T;
}

Arne
 
Back
Top