Syntax for correctly handling null values

When returning an object that may be null, but I shouldn't usually go in with (what is its own name ?!) a very surprised operator: ?? So.

return hazaa ?? new Hazaa(); 

The problem occurs when I return the property of an object (if it exists) and another default value. Not that the nullness check was done on the parent object. Today I like it.

 return hazaa != null ? hazaa.Property : String.Empty; 

I think this is a less than optimal syntax, and I would like it to be more compact (but still easy to understand, given that the property is implemented accordingly).

 return (hazaa ?? new Hazaa()).Property; 

However, I don't like parentheses, and I'm looking for syntax that omits them, still compact. Is there such a thing in C #? I am looking for something like this.

 return hazaa ?.Property :String.Empty; 

And, turning over the thought, something like that.

 return hazaa ?.Property :.BackUpProperty; 

I can create my own properties layer that gives me this behavior, but that just hides the problem. :)

+4
source share
2 answers

If you are interested in this topic, you should read a little about monads. In monad Maybe in particular. This should start: http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/

There is no built-in syntax to simplify null checks in C #, unfortunately.

+2
source

A Perhaps a monad may be a possible alternative

Depending on the implementation, this may look like this:

 May.Be(hazaa, x => x.Property, string.Empty); 

or

 May.Be(hazaa).Select(x => x.Property, string.Empty); 
+3
source

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


All Articles