开发者

Check if a value is null before casting and assigning

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 lawyerRes开发者_运维技巧ponsibleFieldValue = 
    (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.


C# 6 (Visual Studio 2015) introduced Null-Conditionals (aka Elvis operator)...

instead of this...

myObjectValue = (myObjectValue == null) ? null : myObjectValue.child;

the following can be used...

myObjectValue = myObjectValue?.child;


Anywhere you . something, it represents member access, if the left-hand side is a reference type (class) it could be null.

This snippet has several places where a null value might occur:

workflowProperties.Item[lawyerResponsibleUserField.Id].ToString()
                  ^                               ^   ^

I would first of all, break into a debugging session and check what values are present and read up on any documentation regarding the issue. Then I might reconsider writing the code like this.

if (lawyerResponsibleUserField != null
    && lawyerResponsibleUserField.Id != null)
{
    return Convert.ToString(workflowProperties != null 
            ? workflowProperties.Item[lawyerResponsibleUserField.Id] 
            : null
    )
}

Assuming that these properties are reference types and could be null values.

There are many ways to check for null and short circuit the evaluation. A good tip is to avoid using the .ToString() instance method and use the static method Convert.ToString() instead, it doesn't throw an exception if the passed value is null. The return value can still be null, but at least you don't have to worry about the supplied argument as much.


If you want to be really safe:

MyObjectValue myObjectValue = null;

if(myObjectField != null)
{
    object temp = myObjectField.GetFieldValue();
    if(temp != null)
    {
        myObjectValue = (MyObjectValue)temp;
    }
}


I have a feeling that it's actually myObjectField that's null, not myObjectField.GetFieldValue(). If that's the case, then a simple check for null would work fine:

 MyObjectValue myObjectValue;
if  (myObjectField == null)
{
    // recover
}
else 
{
    myObjectValue = (MyObjectValue) myObjectField.GetFieldValue();
}

A few lines of debug code would verify that for you:

Console.WriteLine("myObjectField=" + myObjectField);

If you see null there, then it's myObjectField that's null.


You may have an error elsewhere; if MyObjectValue is a reference type (a class, not a struct), then there should be no exception when casting null to your type. If MyObjectValue is a value type (a struct, not a class), then you cannot assign a null value to it.

You can use the coalescing operator to handle the case for nulls.

MyObjectValue value = (MyObjectValue)(field.GetFieldValue() ?? (object)someValidValue);

someValidValue represents what you'd like to use as the default value in the case that GetFieldValue returns null. This is slightly expensive, since casting someValidValue must be boxed to cast it to an object, but this should do what you're looking for.


Bellow suggestion is just a sample of null values

if object is null then object.ToString() will raise error

in bellow codes i use ComboBox for samples.

so best way is check that

// 1)
if (cmb.SelectedValue == null)
{
   // do something
}

and if you want to use inline

// 2)
string strValue = (cmb.SelectedValue ?? "-1").ToString();
// or
string strValue = cmb.SelectedValue == null ? "-1" : cmb.SelectedValue.ToString();

and last way is to handle error

// 3)
string strValue = "";
try
{
   strValue = cmb.SelectedValue.ToString();
}
catch
{
  strValue = "-1";
}


This should work.

if (myObjectField  != System.DBNull.Value))
{
    string variable = myObjectField.ToString();
}


 public IQueryable GetOrderDetails()
    { 
        var _db = new ProductContext();
        IQueryable<OrderDetail> query = _db.OrderDetails;

        if (ddlOrder.SelectedValue != null && ddlOrder.SelectedItem != null)
        {
            var id = Convert.ToInt32(ddlOrder.SelectedValue);

            query = query.Where(p => p.Username == User.Identity.Name && p.OrderId == id);
                }   
       else{ query = null; ddlOrder.Visible = false;btnSubmit.Visible = false; }
        return query;
           }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜