Casting via generic?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
B

Brett Romero

Is there a way to get a generic type and use it to cast an "object"?
For example:

SomeClass<T>{}

Used as:
SomeClass<MyClass> sc = new SomeClass<MyClass>();

I'd like to get MyClass as a type out of sc and do this:

(sc.GenericType)SomeObject;

or what ever that syntax will look like. Any suggestions?

Thanks,
Brett
 
Brett said:
Is there a way to get a generic type and use it to cast an "object"?
For example:

SomeClass<T>{}

Used as:
SomeClass<MyClass> sc = new SomeClass<MyClass>();

I'd like to get MyClass as a type out of sc and do this:

(sc.GenericType)SomeObject;

or what ever that syntax will look like. Any suggestions?

Thanks,
Brett
The question is why?

You could do something like:
MyGeneric<MyClass> gen = new MyGeneric<MyClass>();
MyClass converted = gen.Convert(myObject);

This would require that myObject can be converted to MyClass or you use
the as operator.

JB
 
Brett Romero said:
Is there a way to get a generic type and use it to cast an "object"?
For example:

SomeClass<T>{}

Used as:
SomeClass<MyClass> sc = new SomeClass<MyClass>();

I'd like to get MyClass as a type out of sc and do this:

(sc.GenericType)SomeObject;

or what ever that syntax will look like. Any suggestions?

Sure - create a generic method, and cast inside that:

void Foo<T>(SomeClass<T> sc)
{
(T) someObject
}

-- Barry
 
Back
Top