C#.NET — Correct delegate call: Identify the correct way to invoke MyFun() in class Sample. class Sample { public void MyFun(int i, float j) { Console.WriteLine("Welcome to CuriousTab !"); } }
-
Adelegate void del(int i); Sample s = new Sample(); del d = new del(ref s.MyFun); d(10, 1.1f);
-
Bdelegate void del(int i, float j); del d; Sample s = new Sample(); d = new del(ref s.MyFun); d(10, 1.1f);
-
CSample s = new Sample(); delegate void d = new del(ref MyFun); d(10, 1.1f);
-
Ddelegate void del(int i, float]); Sample s = new Sample(); del = new delegate(ref MyFun); del(10, 1.1f);
-
ENone of the above
Answer
Correct Answer: delegate void del(int i, float j); del d; Sample s = new Sample(); d = new del(ref s.MyFun); d(10, 1.1f);
Explanation
Introduction / Context:This tests how to correctly declare and use delegates to invoke a method with specific parameters in C#. Correct signature matching is crucial for delegates to work.
Given Data / Assumptions:
- Class Sample has method MyFun(int i, float j).
- We want to call it using a delegate.
Concept / Approach:Delegates must match the method signature exactly. MyFun takes two parameters: int and float. Therefore, the delegate must be declared as delegate void del(int, float).
Step-by-Step Solution:
Option A — Wrong: delegate has only int parameter, but method needs int and float. Option B — Correct: delegate matches method signature and properly instantiates with ref s.MyFun. Option C — Wrong: invalid syntax for delegate instantiation. Option D — Wrong: syntax error in parameter declaration.Verification / Alternative check:Compile and run with Option B, works correctly, printing the message.
Why Other Options Are Wrong:Mismatched signatures or invalid syntax.
Common Pitfalls:Forgetting that delegate parameters must exactly match target method parameters; confusing declaration and instantiation syntax.
Final Answer:delegate void del(int i, float j); del d; Sample s = new Sample(); d = new del(ref s.MyFun); d(10, 1.1f);