Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropertyInfo.GetValue(myObject, null).GetType() returns "Object reference not set to an instance of an object."

I'm trying to convert a MembershipUserCollection to a DataSet to be used in a GridView and I have this helper class that will loop through all the membership rows and properties and get the values and types and shove them into DataRows.

It works while there is a value for the property, but when there is a null value, it breaks returning the message, "Object reference not set to an instance of an object.".

In this particular example, it breaks on the Comment field if when it's value is "null".

Here's my code where it occurs:

    foreach (PropertyInfo oPropertyInfo in PropertyInfos)
    {
        Type oType = oPropertyInfo.GetValue(oData, null).GetType(); <-- error
        oDataRow[oPropertyInfo.Name.ToString()] = Convert.ChangeType(oPropertyInfo.GetValue(oData, null), oType);
    }

Any help is appreciated.

like image 359
Kahanu Avatar asked Feb 25 '23 10:02

Kahanu


1 Answers

GetType() is an instance method. The property value returns either an object or null. Any instance method call on a null reference will cause the error you are receiving. The GetType() method is throwing the exception when you try to call it on a null property (in your case, the Comment property).

You should instead use oPropertyInfo.PropertyType to get the property type, (which is faster anyway).

like image 56
smartcaveman Avatar answered Apr 06 '23 13:04

smartcaveman