Generics a few questions

  • Thread starter Thread starter Jarod
  • Start date Start date
J

Jarod

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 ?
Jarod
 
Jarod said:
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;
 
Jarod said:
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")

I would write this "typeof(GivenType) == typeof(string)", but it is
still quite dodgy code.
// but here I want to do sth like this :
return (GivenType) String.Empty;

A string is castable only to a string or an object. If GivenType was an
int, would you expect the following to work:

return (int) String.Empty;

? How could it?

What are you really trying to do?
But if put String.Empty
into object type and then cast it will work fine.

But then it will *always* throw an exception at run time when GivenType
is neither string nor object.
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 ?

What are you actually trying to do in this method?

-- Barry
 
But then it will *always* throw an exception at run time when GivenType
is neither string nor object.

No it won't - the whole point of the "if" block is to make sure it's
only special-casing a string.

Admittedly the method was missing a return value in other cases, but
something like this will work:

static T GetData<T>()
{
if (typeof(T)==typeof(string))
{
return (T) (object) string.Empty;
}
return default(T);
}
 
Back
Top