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:
func
and take no parameters.int
and the other returns Single
.
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:
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:
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