soandos
soandos

Reputation: 5146

Is it possible to change the return type of a function

Is it possible to have a function that takes (int n,bool wantall) and returns a different type based on the bool? The example that made me think about this was generate the fibonacci numbers. If wantall = true, then return an array (or list) of the first n numbers, else, just return the nth number. Is there a way to do this?

Upvotes: 0

Views: 4481

Answers (7)

slandau
slandau

Reputation: 24102

public Object foo(int n, bool wantall)
{
    // you can return whatever you want
}

Upvotes: 3

AllenG
AllenG

Reputation: 8190

As Jason mentions, using bool for your specific example is not a great idea. However, the issue is really moot using Generics: for instance (using your specific example)

public List<int> FibSequence(int i, int? n)
{
    List<int> fibSeq = new List<int>();
    //Calculate fib sequence
    if(n != null)
    {
       return new List<int>() { fibSeq[n] };
    }
    return fibSeq;
}

Again, for this particular purpose, it's not great, but there are a fair number of times when I have had to get "All of X" when "All" turned out only to be 1 (which would drop the nullable int parameter, but the code itself is very similar). Then your code just handles the generic list that's returned, and considers if it has multiple elements or not.

Upvotes: 0

awright
awright

Reputation: 1234

No, method contracts are defined at compile time and cannot be changed at runtime.

One option would be to return an object type, but the use of the object type in such a circumstance is generally considered to be un-type-safe, so the best practice is to avoid it..

I see a couple ways of handling this:--

  1. Always return an array, but only populate it with one item if wantall=false.
  2. Use separate methods for the single value and the array of values.

Upvotes: 0

Jay Sullivan
Jay Sullivan

Reputation: 18299

You could use a dynamic return type

Upvotes: 0

pickypg
pickypg

Reputation: 22342

Sure. Return an object, or a wrapper that provides an enum that tips you off to what is actually inside the object.

Upvotes: 1

Kyle Trauberman
Kyle Trauberman

Reputation: 25694

You could return object or some other type that all possible return types inherit from, but other than that, you can't change the return type on the fly.

Upvotes: 1

jason
jason

Reputation: 241779

No, you can't change the return type.

For your example, ideally you should have different overloads for what you are talking about

GetFirstFibonacciNumbers(int count)
GetSingleFibonacciNumber(int nth)

Passing in a bool for this is just ugly.

But if you insist on a single method

IEnumerable<int> GetFibonacciNumbers(int n, bool wantall) {
    if(!wantall) {
        return new[] { GetSingleFibonacciNumber(n); }
    }
    else {
        return GetFirstFibonacciNumbers(n);
    }
}

But, please, don't do this.

Upvotes: 10

Related Questions