A little known operator (??) can do away with bulky if...else statements and tidy up the source code. Suppose you want to assign something to a variable, but only want to do so if that value isn't null? Its something I know I do pretty much every day, usually with code such as:
1: if (x != null)
2: {
3: y = x;
4: }
5: else
6: {
7: y = "";
8: }
This can be completely replaced with:
1: y = x ?? "";
How cool is that?
In addition a single (?) can be used as a boolean conditional operator, so instead of testing for null it can test for any boolean to be true. For example:
1: y = x != null ? x : "";
This article was written because of inspiration from both here and here
I'm going to be using these quite a bit I think.
0 comments:
Post a Comment