C# design: If a function sometimes receives an int and sometimes a double, which definition best supports both cases cleanly?

Difficulty: Easy

Correct Answer: static void fun(object i) { ... }

Explanation:


Introduction / Context:
The question explores parameter typing strategies in C# when a method must accept values of different numeric types without duplicating logic.



Given Data / Assumptions:

  • Calls may pass either an int or a double.
  • We want a single method signature that accepts both.


Concept / Approach:
Using object as the parameter type allows any value type to be passed (boxed) or any reference type, enabling one method to accept both int and double. Alternative designs include method overloading (fun(int) and fun(double)), but only one choice here covers both in a single signature.



Step-by-Step Solution:

Consider fun(int): rejects double without conversion.Consider fun(double): rejects int without conversion.Consider fun(object): accepts both after boxing; inside, use is/as or pattern matching to branch.Other signatures add unrelated parameters or contain syntax errors.


Verification / Alternative check:
Pattern matching: if (i is int ii) { ... } else if (i is double dd) { ... }



Why Other Options Are Wrong:

  • fun(int) / fun(double i,int j) / fun(int,double j): Do not meet the stated requirement.
  • Trailing comma version: Syntax error.


Common Pitfalls:
Forgetting that overloading could also solve this but is not among the given valid single-signature options.



Final Answer:
static void fun(object i) { ... }

More Questions from Functions and Subroutines

Discussion & Comments

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