Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value is null before casting and assigning

Tags:

c#

.net-2.0

I'm using c# .net 2.0 and need to check if the value returned from my method that I am assigning my object to is null.

My code is

MyObjectValue myObjectValue= (MyObjectValue) myObjectField.GetFieldValue();

In this instance the value returned by myObjectField.GetFieldValue() could be null and I want to check this before assigning to myObjectValue. At the moment it throws an exception object reference not set to a value of an object.

The actual line of code is using the SharePoint API

SPFieldUserValue lawyerResponsibleFieldValue = 
    (SPFieldUserValue)lawyerResponsibleUserField.GetFieldValue(
              workflowProperties.Item[lawyerResponsibleUserField.Id].ToString());
like image 597
van Avatar asked Dec 03 '22 03:12

van


1 Answers

The above code won't throw a NullReferenceException if myObjectField itself is non-null, unless MyObjectValue is a value type. Are you sure the problem isn't that you're then using myObjectValue without checking whether or not it's null?

However, assuming GetFieldValue returns object, the simplest approach is simply to use a temporary variable:

object tmp = myObjectField.GetFieldValue();
if (tmp != null)
{
    MyObjectValue myObjectValue = (MyObjectValue) tmp;
    // Use myObjectValue here
}

Obviously this will work whether MyObjectValue is a reference type or a value type.

EDIT: Now that you've posted the full line of code, there are loads of places where it could be throwing a NullReferenceException. I strongly suggest that you break up that one line into several lines to find out what's going on.

like image 179
Jon Skeet Avatar answered Dec 16 '22 22:12

Jon Skeet