Comparing a generic type variable with null

  1. What will happen when we try to compare with null in a generic method?
  2. 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");

        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s