Reputation: 5146
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
Reputation: 24102
public Object foo(int n, bool wantall)
{
// you can return whatever you want
}
Upvotes: 3
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
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:--
Upvotes: 0
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
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
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