Safe Navigation operator ?. in C sharp.

Its a very exciting feature in C sharp 6.0 . It makes our work very simple and easier .

Lets take an example here .

Suppose I want to access a grand child value like this

Var value  =  Parent.Child.Child.Child ;

So in this above query there is chance of getting the Null value from any of the object like Parent or Child one. If possibly Parent or Child value will be Null in run time it will  through the NullReferenceException .

This above object accessing logic can be handled it in other way like conditional statement or Ternary operator as well . But Instead of applying this how we can handle it by Safe Navigation operator ?.

This operator can be written as

Var value  =  Parent ?.Child ?. Child ?. Child ;

The Safe Navigation operator will check if the object to the left is not null , then fetch what  is to the right else return null and halt the access chain.

This is how the safe Navigation operator works in c sharp.

Enjoy .... Keep coding ....


Comments

Popular posts from this blog

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

The transaction is aborted or Failure while attempting to promote transaction.

Unable to load one or more breakpoints in Visual studio.