Random C# Tricks
I wanted to share a few C# tricks I reviewed today. Some programmers will use them all the time, others barely know about their existence.
In this short source code example I will be demoing the ?? operator, chaining ??, and String.IsNullOrWhiteSpace() which is a newer .NET method.
So here is the source I’ll talk about:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | |
The ?? operator is a simple way to set a variable to something, and if that first condition is null it will fallback to a second value. So since x is null, y will end up being set to 30. The program outputs the expected result to prove that.
Next we will chain the ?? operators together. In my example both x and w are null, so z will have to be set to (y + 1), or 31. The program again prints the expected result to screen.
The benefit that ?? brings to the table is that it turns what could have been a complicated if/else statement, into a logic one-liner. It is also a nice convenience since you can write code that may or may not have to deal with an uninstantiated variable at runtime very easily.
Finally, I have a block of code that shows how the new String.IsNullOrWhiteSpace() method from .NET version 4 works. Basically, the method returns true if a given string is null, or just a bunch of whitespace; otherwise it will return false. So I send in a null, a string with just spaces, and a string with a phrase and I print the expected results to screen. This method could be helpful to determine if the user entered in a space or spaces when in reality it should have been sent in as null or just empty.
Here is a screenshot of the running program:
I found these either new or exciting to use today, and I hope you can find interesting ways to incorporate them in your software design!
