- What will happen when we try to compare with null in a generic method?
- What will happen when we define the struct constraint?
The C# compiler allows us to compare with null in generic methods. When we specify a generic type parameter with a value type the C# compiler won’t emit code containing inside if == null test and always will emit code containing inside if != null test.
Example 1:
private static void CompareWithNull<T>(T param)
{
if (param == null)
Trace.WriteLine("== operator");
if (param != null)
Trace.WriteLine("!= operator");
}
When we define the struct constraint the C# compiler will generate a compiler time error.
Example 2:
private static void CompareWithNull<T>(T param) where T : struct
{
//Operator ‘==’ cannot be applied to operands of type ‘T’ and ‘<null>’
if (param == null)
Trace.WriteLine("== operator");
//Operator ‘!=’ cannot be applied to operands of type ‘T’ and ‘<null>’
if (param != null)
Trace.WriteLine("!= operator");
}