C#.NET generics — What will the following code do?
public class TestCuriousTab
{
public void TestSub(M arg)
{
Console.Write(arg);
}
}
class MyProgram
{
static void Main(string[] args)
{
TestCuriousTab tab = new TestCuriousTab();
tab.TestSub("CuriousTab ");
tab.TestSub(4.2f);
}
}
-
AProgram will compile and on execution will print: CuriousTab 4.2
-
BA non generic class Hello cannot have generic subroutine.
-
CCompiler will generate an error.
-
DProgram will generate a run-time exception.
-
ENone of the above.
Answer
Correct Answer: Program will compile and on execution will print: CuriousTab 4.2
Explanation
Introduction / Context:This question assesses understanding of generic methods declared inside non-generic classes and how type inference and Console.Write formatting behave at runtime.
Given Data / Assumptions:
- TestCuriousTab is a non-generic class.
- Method TestSub
(M arg) is a generic method. - Calls are made with a string and a float (Single).
Concept / Approach:In C#, a class need not be generic to contain generic methods. The compiler infers M from the argument type at each call site (string then Single). Console.Write writes values back-to-back without newline; string "CuriousTab " includes a trailing space; Single value 4.2f prints as 4.2 with invariant formatting in typical console settings.
Step-by-Step Solution:
First call: M inferred as string → prints "CuriousTab ".Second call: M inferred as Single → prints "4.2".Combined output (no newline): "CuriousTab 4.2".Verification / Alternative check:Change Console.Write to Console.WriteLine to see each on a new line; or pass an int to verify type inference continues to work.
Why Other Options Are Wrong:
- B: Non-generic classes can have generic methods.
- C/D: There is no compile-time or runtime error; generics are used correctly.
- E: Option A is correct.
Common Pitfalls:Believing only generic classes can define generic methods; confusing Write with WriteLine when predicting exact output spacing.
Final Answer:Program will compile and on execution will print: CuriousTab 4.2