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
No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).
Two or more methods can have the same name inside the same class if they accept different arguments. This feature is known as method overloading.
Signatures are the enabling mechanism for overloading of members in classes, structs, and interfaces. Overloading of methods permits a class, struct, or interface to declare multiple methods with the same name, provided their signatures are unique within that class, struct, or interface.
The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With