PC Review


Reply
Thread Tools Rate Thread

Casting via generic?

 
 
Brett Romero
Guest
Posts: n/a
 
      25th Jul 2006
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

 
Reply With Quote
 
 
 
 
John B
Guest
Posts: n/a
 
      25th Jul 2006
Brett Romero wrote:
> 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

 
Reply With Quote
 
Barry Kelly
Guest
Posts: n/a
 
      25th Jul 2006
"Brett Romero" <(E-Mail Removed)> wrote:

> 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

--
http://barrkel.blogspot.com/
 
Reply With Quote
 
 
 
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Generic casting =?Utf-8?B?TWlydHVs?= Microsoft C# .NET 3 15th May 2007 10:38 PM
Casting in a generic function Vincent Finn Microsoft C# .NET 3 28th Mar 2007 02:54 PM
Down-casting of Typed Collection (Casting Generic Types?) conchur Microsoft C# .NET 1 3rd Jul 2006 11:45 AM
casting in generic 3nc0d3d@gmail.com Microsoft VC .NET 2 26th Apr 2006 08:48 AM
Generic collection casting =?Utf-8?B?Y3lsdA==?= Microsoft Dot NET 2 14th Apr 2006 05:33 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 06:37 AM.