I'm trying to return a T type value.
public T this[int index]
{
get
{
if (typeof(T) == typeof(int))
return (T) dynEx[index].Int;
else if (typeof(T) == typeof(string))
return (T) dynEx[index].Str;
}
}
dynEx is a complex object that returns an object based on some custom expression.
The code above obviously doesn't work because it has an error: "cannot convert type 'int' to T" and "cannot convert type 'string' to T".
How can I achieve this without having a performance impact?
This property is called more than a thousand times per frame (it's a game).
In order to cast to int
, you'll need to cast the result to object
first, potentially boxing. It's annoying, but unfortunately it's a limitation of C# generics - for good reasons that escape me right now, unfortunately. So you want:
public T this[int index]
{
get
{
if (typeof(T) == typeof(int))
{
return (T) (object) dynEx[index].Int;
}
else if (typeof(T) == typeof(string))
{
return (T) (object) dynEx[index].Str;
}
// TODO: Whatever you want to happen if T isn't int/string
}
}
See more on this question at Stackoverflow