How to define a null reference in C #?

How to determine if an object reference is null in C # without throwing an exception if it is null?

i.e. If I have a reference to the class and I don't know if it is null or not.

+4
source share
10 answers

What Robert said, but in this particular case, I would like to express it with a security proposal like this, instead of embedding the entire method block in an if block:

void DoSomething( MyClass value ) { if ( value == null ) return; // I might throw an ArgumentNullException here, instead value.Method(); } 
+8
source

testing against null will never * throw an exception

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

* never, never, never. As @Ilya Ryzhenkov points out, an incorrect statement implementation! = For MyClass may raise an exception. Fortunately, Greg Buck has a good blog post about implementing object equality in .NET .

+15
source

Please note that the presence of the operator! = defined on MyClass will likely result in a different check result and a NullReferenceException later. To be absolutely sure, use object.ReferenceEquals (value, null)

+5
source
 if(p != null) { DoWork(p); } 

In addition, the “how” keyword is useful if you want to determine if a class has the correct type and use it all at once.

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

In the above example, if you selected e like (IExample) e, it will throw an exception if e does not implement IExapmle. If you use 'as' and e does not implement IExample, e will just be null.

+4
source

If you look at most of the .NET Framework source codes, you will see that 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 } 
+4
source

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 there will be no exceptions.

+3
source

This is nothing, but I always code them as ...

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

instead

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

to avoid accidental recording

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

because

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

will give you a compiler error

+1
source
 (YourObject != Null) 

can you compare with null?

If it is null instead of throwing an exception, you can initialize your object. You can use the null pattern.

0
source

Or, if you use value types, you can read about types with NULL capability: http://www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx

0
source

I have a definition of a xaml.cs derivative application in my application:

 private SortedList myList; 

And I want to be able to reuse my constructors. Therefore I need:

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

Thanks Robert!

0
source

Source: https://habr.com/ru/post/1277748/


All Articles