V3111. Checking value for null will always return false when generic type is instantiated with a value type.
The analyzer detected a comparison of a generic-type value with 'null'. If the generic type used has no constraints, it can be instantiated both with value and reference types. In the case of a value type, the check will always return 'false' because value types cannot have a value of null.
Consider the following example:
class Node<T>
{
T value;
void LazyInit(T newValue)
{
if (value == null) // <=
{
value = newValue;
}
}
}
If 'T' is defined as a value type, the body of the 'if' statement will never execute and the 'value' variable will fail to be initialized to the value passed, so its value will always remain the 'default' value of 'T'.
Use constraints if you need to handle objects of reference types only. For example, you can use a constraint on the generic type 'T' in the code above so that it could be instantiated only with reference types:
class Node<T> where T : class // <=
{
T value;
void LazyInit(T newValue)
{
if (value == null)
{
value = newValue;
}
}
}
If you want the generic type to work with both value and reference types and you want the check to work with values of both, test the value for the type's default value instead of 'null':
class Node<T>
{
T value;
void LazyInit(T newValue)
{
if (object.Equals(value, default(T))) // <=
{
value = newValue;
}
}
}
In this case, the check will work properly with both reference and value types. However, if you want to apply it only to reference types with a null value (without constraints on the 'T' type), do the following:
class Node<T>
{
T value;
void LazyInit(T newValue)
{
if (typeof(T).IsClass && // <=
object.Equals(value, default(T)))
{
value = newValue;
}
}
}
The 'IsClass' method will return 'true' if the generic type was instantiated with a reference type, so only reference-type values will be tested for the type's default value, like in the previous example.