Search code examples
c#klocwork

Reference 'GetUnderlyingType' return from call to function 'GetUnderlyingType' may be null


I am getting below Klocwork issue, while doing code analysis,

Reference 'GetUnderlyingType' return from call to function 'GetUnderlyingType' may be null

if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                {
                    value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                    objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                }
                else
                {
                    value = row[columnname].ToString().Replace("%", "");
                    objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
                }

enter image description here


Solution

  • From the documentation

    Return Value
    Type: System.Type

    The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null

    You handle this with your outer if clause, but VisualStudio doesn't seem to recognize it. The solution would be this:

    var ut = Nullable.GetUnderlyingType(objProperty.PropertyType);
    if (ut != null)
    {
        value = row[columnname].ToString().Replace("$", "").Replace(",", "");
        objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(ut.ToString())), null);
    }
    else
    {
        value = row[columnname].ToString().Replace("%", "");
        objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
    }