public class Foo {
private int barI;
private float barF;
public <what would go here?> Get( bool isInt ) {
if (isInt) return barI;
else return barF;
}
}
… where a single method can return an int or a float depending on circumstances. But I suspect it’s impossible… or is it?
Unfortunately because numbers don’t have a consistent inheritence hierarchy this is difficult to do in the Mono/.Net platform. This is a post on SO about this and it’s a known ‘feature’. Oddly enough C# does not have a constraint that says void TThing GetThing(bool b) where TThing : some number. A pretty gaping hole in their generics IMHO. numbers have some common ancestry (the Single class and all it’s interfaces) but this hierarchy cannot be used as a constraint and even if it could there are no operators on it anyway that you would typically care about. All the operators are defined elsewhere.
You can create a constraint that accepts only float and int, but unfortunately it can’t perform the cast to T in this case. Generics work different than C++ templates.
public class Foo
{
private int barI;
private float barF;
public T Get<T>() where T : float,int
{
T tmp;
if (tmp is int)
return (T)barI; // WON'T WORK !
else
return (T)barF; // WON'T WORK !
}
}