tags:

views:

140

answers:

5

In C#, is it possible to have same parameters yet override each other(they are different in the return types)

public override Stocks[] Search(string Field,string Param){ //some code}
public override Stocks Search(string Field, string Param){//some code}

C# returns compilation error

A: 

As far as I know, it is not possible.

Even if it is, it's unnecessarily complicated. Just return an array in all cases (if only one value is returned, then it's an array of Stocks[1]). That should save you some time, especially since C# makes using arrays pretty simple.

peachykeen
+7  A: 

In C#, you can only overload methods that have different signatures.

The return type of a method is not included in the signature - only the method name, types and number of parameters (and their order). The two examples have the same signature, so they cannot exist together.

Classically, one can return a list of items (array or other data structure) - if only one item is required, you simply return a list with one item.

Oded
I think, I will go with a list
Soham
A: 

No - the compiler throws an error because it only uses the parameters to detemine which method to call, not the return type.

Adam V
@Adam V - it also uses the method name ;)
Oded
@Oded - figured it wasn't necessary to say that. :)
Adam V
@Oded, :) Not as if the compiler would run around looking for all possible methods that accepts the specific parameter sequence regardless of the name... Sorry the thought made chuckle so I had to share.
Chris Taylor
A: 

No, you can't.

CLR allows it, but for some reason, the C# dudes decided not to use this CLR feature.

Daniel Dolz
It's hard to support in a language that's supposed to be a member of the C family, whose members generally have no notion of context-dependent evaluation.
Jon Purdy
+2  A: 

As Oded already points out in his answer, it is not possible to overload a method when the only difference is the return type.

public override Stocks[] Search(string Field,string Param){ //some code}
public override Stocks Search(string Field, string Param){//some code}

Think about it: How should the compiler know which method variant to call? This apparently depends on your search result, and obviously the compiler can't know that in advance.

In fact, what you want is one function which has two possible return types. What you don't want is two separate methods, because you'd then have to decide up-front which one to call. This is obviously the wrong approach here.

One solution is to always return an array; in case where only one Stocks object is found, you return an array of size 1.

stakx