Overload with the same parameter signature

In C #, is it possible to have the same parameters, but override each other (they differ in 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

+6
c # overloading
source share
6 answers

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

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

Classically, you can return a list of elements (an array or another data structure) - if only one element is required, you simply return a list with one element.

+11
source share

As Oded already pointed out in his answer, it is not possible to overload the 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 can the compiler know which variant of the method to call? This obviously depends on your search result, and obviously the compiler cannot know this in advance.

Actually what you need is one function that has two possible return types. What you do not want are two separate methods , because then you will need to decide which side to call. This is obviously the wrong approach.

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

+3
source share

In a sense, using several 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; } } 
+1
source share

As far as I know, this is not possible.

Even so, it is unnecessarily complicated. Just return the array in all cases (if only one value is returned, then this is an array of stocks [1]). This should save you some time, especially since C # makes using arrays quite simple.

0
source share

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

0
source share

No, you can’t.

The CLR allows this, but for some reason C # dudes decided not to use this CLR function.

0
source share

All Articles