Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a NullReferenceException

Tags:

c#

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?

like image 271
lolli Avatar asked Jul 23 '12 11:07

lolli


People also ask

What does system NullReferenceException mean?

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.

Why am I getting a null reference exception?

A NullReferenceException happens when you try to access a reference variable that isn't referencing any object. If a reference variable isn't referencing an object, then it'll be treated as null .

Can I throw NullReferenceException?

You should never throw a NullReferenceException manually. It should only ever be thrown by the framework itself. From the NullReferenceException documentation: Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.


1 Answers

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.

like image 177
James Avatar answered Nov 09 '22 21:11

James