Soham
Soham

Reputation: 873

Overloading with same parameter signature

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

Upvotes: 6

Views: 8098

Answers (6)

SpeedCoder5
SpeedCoder5

Reputation: 9018

In a way by using multiple interfaces:

struct Stock { public string Symbol; public decimal Price;}
interface IByArray { Stock[] Search(string Field, string Param); }
interface IByClass { Stocks Search(string Field, string Param); }
class Stocks : IByArray, IByClass
{
    Stock[] _stocks = { new Stock { Symbol = "MSFT", Price = 32.83m } };
    Stock[] IByArray.Search(string Field, string Param)
    {
        return _stocks;
    }
    Stocks IByClass.Search(string Field, string Param)
    {
        return this;
    }
}

Upvotes: 1

Oded
Oded

Reputation: 499372

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.

Upvotes: 11

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.

Upvotes: 3

Daniel Dolz
Daniel Dolz

Reputation: 2421

No, you can't.

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

Upvotes: 0

Adam V
Adam V

Reputation: 6356

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

Upvotes: 0

ssube
ssube

Reputation: 48337

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.

Upvotes: 0

Related Questions