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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With