0

I'm getting a NULL reference exception for code that runs after I attempted to filter out null values for a list of _PropertInfo objects using LINQ.

The error occurs in the foreach loop of the CheckAutoPatientLookupProperties method.

The exact exception read:

An unhandled exception of type 'System.NullReferenceException' occurred in InterfacePatientAutoMatch.exe

Additional information: Object reference not set to an instance of an object.

AutoPatientLookup APIParameters = new AutoPatientLookup();

//to be used only for testing
APIParameters = InitializeTestPatientInfo();
CheckAutoPatientLookupProperties(APIParameters);

public static AutoPatientLookup InitializeTestPatientInfo(bool SSN = false, bool PatientNumber = false, bool Gender = false)
{
    AutoPatientLookup TestAPIParameters = new AutoPatientLookup();
    TestAPIParameters.FirstName = "First";
    TestAPIParameters.LastName = "Last";
    TestAPIParameters.DOB = "4/9/1953";
    if (SSN)
    {
        TestAPIParameters.SSN = 00000000;
    }
    if (PatientNumber)
    {
        TestAPIParameters.PatientNumber = 000;
    }
    if (Gender)
    {
        TestAPIParameters.Gender = "F";
    }

    return TestAPIParameters;
}

public static void CheckAutoPatientLookupProperties(AutoPatientLookup TestObj)
{

    foreach (_PropertyInfo Property in TestObj.GetType().GetProperties().Where(Property => Property != null))
    {
        Console.WriteLine("AutoPatientLookup Instance Property {0} = {1}", Property.Name, Property.GetValue(TestObj,null).ToString());
    }

    Console.ReadKey();
}

public class AutoPatientLookup
{
    public string DOB { get; set; }
    public string Gender { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int PatientNumber { get; set; }
    public int SSN { get; set; }
}

By hovering over Property.GetValue(TestObj,null) while debugging I found it to be null when the method looped over the Gender property, which isn't initialized in the InitializeTestPatientInfo method.

Is there something wrong with my LINQ expression when outlining my foreach loop? Shouldn't it have skipped to Gender property? I don't get any compile time errors so I think my expression is legal, but it's not being honored.

Any help appreciated.

johnny 5
  • 16,589
  • 46
  • 82
  • 156
W.Harr
  • 193
  • 3
  • 11
  • If it is coming from database try DB.null. – jdweng May 11 '18 at 17:07
  • 6
    `TestObj.GetType().GetProperties().Where(Property => Property != null)` isn't filtering properties where their values are null... it's filtering PropertyInfo objects against being null. – Llama May 11 '18 at 17:07
  • @john If you're comment were an answer I would mark it as right – W.Harr May 11 '18 at 18:08

0 Answers0