Re: Generics a few questions



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
.



Relevant Pages

  • Generics a few questions
    ... // I need to check if GivenType is System.String ... When I try to cast on GivenType which is in this case for 100% string I got error in compile time, ... But if put String.Empty into object type and then cast it will work fine. ... Jarod ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Generics a few questions
    ... // I need to check if GivenType is System.String ... A string is castable only to a string or an object. ... return (int) String.Empty; ... into object type and then cast it will work fine. ...
    (microsoft.public.dotnet.languages.csharp)