C#.NET overloading — What is wrong with the following code and which statement is correct? namespace CuriousTabConsoleApplication { class Sample { public int func() { return 1; } public Single func() { return 2.4f; } } class Program { static void Main(string[] args) { Sample s1 = new Sample(); int i; i = s1.func(); Single j; j = s1.func(); } } }

Difficulty: Medium

Correct Answer: func() cannot be considered overloaded because: return value cannot be used to distinguish between two overloaded functions.

Explanation:


Introduction / Context:
In C#, method overloading is based on the method signature, which includes the method name and parameter list, but excludes the return type. This example attempts to define two methods that differ only by return type.



Given Data / Assumptions:

  • Both methods are named func and take no parameters.
  • One returns int and the other returns Single.
  • Main attempts to call both.


Concept / Approach:
Because the parameter lists are identical (empty) and names are the same, the two declarations collide. The compiler cannot choose an overload based solely on the expected return type at a call site; therefore, this code does not compile. Legal overloading would require distinct parameter lists.



Step-by-Step Solution:

1) Compare signatures: name + parameters are identical — not allowed.2) Observe that return type is ignored for overload resolution.3) Conclude that the code is a compile-time error; neither call is valid as written.


Verification / Alternative check:
Attempting to compile yields a method with the same name and signature error. Changing one method to func(int x) or similar resolves it.



Why Other Options Are Wrong:

  • A: Incorrect — this is not valid overloading.
  • B: Incorrect — functions can be overloaded; the rule applies equally to methods with return values.
  • D/E: These presume the program compiles; it does not in this form.


Common Pitfalls:
Thinking the compiler can pick an overload from the assignment target's type; C# does not allow overloading by return type alone.



Final Answer:
Return type cannot be used to distinguish overloaded methods; the code does not compile.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion