简体   繁体   中英

How do I detect a null reference in C#?

How do I determine if an object reference is null in C# w/o throwing an exception if it is null?

ie If I have a class reference being passed in and I don't know if it is null or not.

testing against null will never* throw an exception

void DoSomething( MyClass value )
{
    if( value != null )
    {
        value.Method();
    }
}

* never as in should never . As @Ilya Ryzhenkov points out, an incorrect implementation of the != operator for MyClass could throw an exception. Fortunately Greg Beech has a good blog post on implementing object equality in .NET .

What Robert said, but for that particular case I like to express it with a guard clause like this, rather than nest the whole method body in an if block:

void DoSomething( MyClass value )
{
    if ( value == null ) return;
    // I might throw an ArgumentNullException here, instead

    value.Method();
}

Note, that having operator != defined on MyClass would probably lead do different result of a check and NullReferenceException later on. To be absolutely sure, use object.ReferenceEquals(value, null)

if(p != null)
{
   DoWork(p);
}

Also, the 'as' keyword is helpful if you want to detect if a class is of the right type and use it all at once.

IExample e = p as IExample;
if(e != null)
    DoWork(e);

In the above example if you were to cast e like (IExample)e it will throw an exception if e does not implement IExapmle. If you use 'as' and e doesn't implement IExample e will simply be null.

If you look in the majority of the .NET framework source code you will see they put checks like this at the top of their functions.

public void DoSomething(Object myParam)
{
  if (myParam == null) throw new ArgumentNullException("myParam");

  // Carry on
}

With C# 6.0 this is much more elegant; you can do it in one line :-)

value?.Method();

If "value" is null, nothing will happen - and no exception.

It's nit picky, but I always code these like ...

if (null == obj) {
   obj = new Obj();
}

instead of

if (obj == null) {
   obj = new Obj();
}

to avoid accidently writing

if (obj = null) {
   obj = new Obj();
}

because

if (null = obj) {
   obj = new Obj();
}

will give you a compiler error

(YourObject != Null)

you can compare to null?

If it's null instead of throwing an exception you can initialize your object. You can use the Null Pattern.

或者,如果您使用值类型,则可以阅读有关可空类型的内容: http//www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx

I have in the application's xaml.cs application derivative definition:

private SortedList myList;

And I want to be able to re-use my constructors. So I needed:

if ( myList == null)
   myList = new SortedList();

Thanks Robert!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM