ReSharper 2016.2 Help

Code Inspection: Possible compare of value type with 'null'

Consider the following piece of code:

static void PrintItems<T>(List<T> items) { foreach (var item in items) { if (item != null) { Console.WriteLine(item.ToString()); } } }

While it may not be obvious at first, the T type can, in fact, be a value type (e.g., a struct or an integer). This would lead to the comparison being ignored altogether, which might not be what the user has intended.

One option for resolving this would be to constrain the T parameter to class types:

static void PrintItems<T>(List<T> items) where T : class { ... }

The other option would be to change the comparison value from null to the default value for the particular type:

if (!Equals(item, default(T))) { Console.WriteLine(item.ToString()); }

See Also

Last modified: 15 December 2016