JetBrains Rider 2023.2 Help

Code Inspection: Possible comparison 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 (for example, a struct or an integer). This would lead to the comparison being ignored altogether, which might not be what the user has intended.

JetBrains Rider does not suggest any quick-fixes here because there is no simple way to check all possible value types of the T.

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 { //... }

However, after such fix you'll have to make sure that all usages of PrintItems<T>() satisfy the generic constraint.

Last modified: 08 March 2021