lolli
lolli

Reputation: 143

Getting a NullReferenceException

I'm getting this:

    private object setReportValues(object report, FormCollection values)
    {
        PropertyInfo[] properties = report.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            string val = values.GetValue(property.Name).ToString();
            property.SetValue(report, val, null);
        }
        return report;
    }

Exception is on string val = values.GetValue(property.Name).ToString();. Do I have to check for nulls before?

Upvotes: 7

Views: 5712

Answers (4)

Mike Hohne
Mike Hohne

Reputation: 472

Just ran into this same issue, but I found a solution without having to use a loop:

private object setReportValues(object report, FormCollection values)
{
    PropertyInfo[] properties = report.GetType().GetProperties();
    foreach (PropertyInfo property in properties)
    {
        string val = values.GetValue(property.Name)?.ToString();
        property.SetValue(report, val, null);
    }
    return report;
}

I fixed it by adding a ? (new feature in C# 6.0 I believe) after the ...property.Name).

Upvotes: 1

Gaute Løken
Gaute Løken

Reputation: 7892

I'm gonna go out on a limb and suggest that there's no property with the provided property.Name in values. So your call to values.GetValue returns a null. When you try to do ToString() on that null value, it complains.

In short, what does your values variable contain?

Update:

With the provided information that values is a FormsCollection it is quite probable that your properties collection contains a few properties for which you have no FormsCollection field. And what happens is that you try to get this field, it returns a null value and you call ToString on that, causing everything to break.

I would invert my strategy and loop through my FormsCollection getting the properties 1 by 1 as you encounter them. The alternative is to keep it as you have it and check for null before doing a ToString.

PS: I hope all of your properties represented on the form are strings, or things will break.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062492

Why would you force .ToString() ? null is a perfectly legal value for most things. It isn't clear what values is, so I assume that is coming from your own code, but:

object val = values.GetValue(property.Name);
property.SetValue(report, val, null);

Depending on what values is, you might also want to check the difference between "has a value, that is null" vs "doesn't have any defined value". Personally, I would expect to do something like:

object val;
if(values.TryGetValue(property.Name, out val)) {
    property.SetValue(report, val, null);
}

Upvotes: 0

James
James

Reputation: 82096

Do I have to check for nulls before?

On this line, yes:

string val = values.GetValue(property.Name).ToString()

Simply because the value of that particular property could be null.

Upvotes: 5

Related Questions