C#.NET generics — What happens in this generic class when using an operator on T?
public class Generic
{
public T Field;
public void TestSub()
{
T i = Field + 1;
}
}
class MyProgram
{
static void Main(string[] args)
{
Generic gen = new Generic();
gen.TestSub();
}
}
-
AAddition will produce result 1.
-
BResult of addition is system-dependent.
-
CProgram will generate run-time exception.
-
DCompiler will report an error: Operator '+' is not defined for types T and int.
-
ENone of the above.
Answer
Correct Answer: Compiler will report an error: Operator '+' is not defined for types T and int.
Explanation
Introduction / Context:This problem explores generic type constraints and operator use in generic code. Can we write expressions involving T without constraining T to types that support those operators?
Given Data / Assumptions:
- Class Generic
defines TestSub with expression T i = Field + 1. - No constraints (where T : ...) are specified.
- Caller instantiates Generic
but the generic code is compiled for arbitrary T.
Concept / Approach:In C#, operator resolution for generics is performed at compile time against the type parameter T, not the eventual closed type. Without constraints, the compiler cannot assume T supports operator + with an int. Therefore, the code does not compile. Adding constraints does not help because operators are not part of constraints; a typical approach is to use generic math interfaces (in newer C# with System.Numerics) or provide strategies (delegates/interfaces) for arithmetic.
Step-by-Step Solution:
Examine TestSub: T i = Field + 1 → requires + between T and int.No constraint tells the compiler that + exists for T.Compiler error: operator '+' cannot be applied to operands of type 'T' and 'int'.Verification / Alternative check:Replace T with int directly (non-generic) and it compiles; or change the method to accept a Func
Why Other Options Are Wrong:They imply successful compilation or runtime behavior; failure happens at compile time.
Common Pitfalls:Expecting generics to be duck-typed at compile time; C# generics are statically checked.
Final Answer:Compiler will report an error: Operator '+' is not defined for types T and int.