Tuesday, September 20, 2011

Some Lesser Known C# Operators

Some Miscellaneous Coding Tips


?? is a C# binary operator used to provide a default value should the left operand be null. For example:

1X = A ?? B;

equates to:
1if(A != null)
2  X = A;
3else
4  X = B;


Relatively simple, but a great time saver, and sometimes quite useful. Another example:
1string result = ( TextBox1 ?? new TextBox() ).Text;

In this example, if TextBox1 is not null, result will contain TextBox1.Text. Otherwise, it will contain a blank string, since that is what new TextBoxes are initialized to.

Another example, one that I actually use all the time:
System.Windows.Controls.CheckBox.IsChecked is a nullable bool, meaning its value can be either true, false, or null. I want to equate null to false. Here's how I'd do it:

1//myCheckBox is a checkbox defined in the XAML file
2if(myCheckBox.IsChecked ?? false)
3    someLogicHere;


If the checkbox's state is null, it is replaced with the value false.

=======================================================

?: is a C# (and many other languages) ternary operator used to return a value based on the evaluation of a boolean expression. This one is far more commonly known than the ?? operator, because it has its roots in C, but I'm still surprised at how many people don't know how to use it. Here's an example of how it works:

1X = A ? B : C;

This is equivalent to:
1if(A)
2  X = B;
3else
4  X = C;


A more practical example:
1string substr = fullstr.Length > 10 ? fullstr.Substring(0, 10) : fullstr;

This code sets substr's value to the first 10 characters of fullstr, unless fullstr is shorter than 10 characters, in which case, substr is assigned the value of fullstr.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More