Can I create a c# method which might return different types?

I want to do something along the lines of this:

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 have the method return object like so:

private int barI;
private float barF;

private object Get(bool isInt)
{
    if (isInt)
        return barI;
    else return barF;
}

But you’d have to cast the returned object to the correct type when you call the method:

int integer = (int)Get(true);
float single = (float)Get(false);

If you get that mixed up and try to cast the returned object to something it isn’t, you’re in trouble.

I guess you could return a hashtable, and check the existing keys in it to see what was returned.

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 !
    }
}