Re: Generics a few questions
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Mon, 29 May 2006 20:43:21 +0100
Jarod <blueice@xxxxxxxxxxxxxxxx> wrote:
Hey
I have function like this:
GivenType GetData<GivenType>(...)
{
// I need to check if GivenType is System.String
the only way I found to work was:
if(typeof(GivenType) == Type.GetType("System.String")
// but here I want to do sth like this :
return (GivenType) String.Empty;
}
When I try to cast on GivenType which is in this case for 100% string I got
error in compile time, that casting is impossible. But if put String.Empty
into object type and then cast it will work fine. But it seems like not so
efficient so maybe there is a better way ? How to check for type on
GivenType any other ways than typeof ?
Well, aside from the fact that I'd use typeof(string) instead of
Type.GetType("System.String") I don't think the above is too bad, with
the extra cast to object just to make it compile:
return (GivenType) (object) string.Empty;
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- References:
- Generics a few questions
- From: Jarod
- Generics a few questions
- Prev by Date: webform password protected page
- Next by Date: Re: Enums and IEquatable<T>
- Previous by thread: Generics a few questions
- Next by thread: Re: Generics a few questions
- Index(es):
Relevant Pages
|