using Type

  • Thread starter Thread starter Jinsong Liu
  • Start date Start date
J

Jinsong Liu

I have a function, which accept two parameters, one is a object,
another is a Type. I need to cast the object to the type define by
Type. is it possible?

void MyFunction(Object O, Type T)
{
// this is what I want to do
T MyObject=(T)O;
}
 
Jinsong,

You can't do this without Generics, you could do something like this:

void MyFunction<T>(object o)
{
T MyObject = (T) o;
}

However, that's kind of pointless, because you could just do this then:

void MyFunction<T>(T o)
{
// Use o here as T.
}

This is better, since it will throw a compiler error if the object you
pass is not of type T (or derived from T).

In .NET 1.1 you should define a common interface that the instances
implement and then make your parameter that.

Hope this helps.
 
Hi,

No, you cannot do that.

What is what you want to do?

You could use reflection to call members of T though.
 
Nicholas Paldino, why wont this work?

String strA;
int i = (int) strA;

// gives the error can't cast string to integer (or something like
that)

Obinna.
Jinsong,

You can't do this without Generics, you could do something like this:

void MyFunction<T>(object o)
{
T MyObject = (T) o;
}

However, that's kind of pointless, because you could just do this then:

void MyFunction<T>(T o)
{
// Use o here as T.
}

This is better, since it will throw a compiler error if the object you
pass is not of type T (or derived from T).

In .NET 1.1 you should define a common interface that the instances
implement and then make your parameter that.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Jinsong Liu said:
I have a function, which accept two parameters, one is a object,
another is a Type. I need to cast the object to the type define by
Type. is it possible?

void MyFunction(Object O, Type T)
{
// this is what I want to do
T MyObject=(T)O;
}
 
Back
Top