Awesome Operators

Some operators are just more awesome than others. Here are some of my faves. Let’s start with the ternary conditional operator (?:). I have loved this one since C, and is one of those that cannot be overloaded (another awesome feature) in C++. Here’s its definition:

condition ? first_expression : second_expression;

If the condition is true, the first_expression is returned, and second_expression if false. You can think of it as a good one liner for an if-else expression. Very useful when you want to stick a conditional evaluation into another expression, such as a function call. Here are some examples of use:

    uint u = hours.TotalMinutes > 0 ? Convert.ToUInt32(hours.TotalMinutes) : 0;

 

    // For nullable types

    data.Content = row.items.HasValue ? row.items.Value : 0;

 

    string.Format(“Has Value: {0}”, count > 0 ? “TRUE” : “FALSE”);

 

    var v = b ? Foo(“Yes”) : Bar(“No”);

 

 

As you can see, it’d be not as brief writing the above with if-else expressions.

 

This brings me to the next awesome operator… The null-coalescing operator (??). From MSDN:

 

“The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.”

 

So this operator is like a specialized ternary conditional operator for null’s. Isn’t that neat? Here are some example uses:

 

 

      private void Foo(List<string> items)

      {

            DoSomethingWithList(items ?? new List<string>());

      }

 

      Debug.WriteLine(“Message: {0}”, message ?? “There is no message”);

 

      // For nullable types

      int? magic = GetMagicNumber();

      int result = magic ?? 0;

 

 

I think it’s a great convenience for handling null’s, and works well with Nullable types of course. And for those who are not aware of Nullable types, it’s another neat feature of .NET. It can be defined in two ways (from MSDN):

 

System.Nullable<T> variable

-or-

T? variable

T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.

 

You may have happened upon situations where you have parameters that are value types that can be ‘ignored’. But since they are value types and not reference types, you can’t get a value of null to have it indicate that you should ignore it. For example:

      private void Foo(int value1, int value2)

      {

            // I want the caller to be able to let me know

            // if they want they parameters to be processed

            // or not. Maybe only positive values are valid

            if (value1 >= 0)

            {

                  DoSomething(value1);

            }

 

            if (value2 >= 0)

            {

                  DoSomething(value2);

            }

 

      }

 

Well, in a language like C/C++ that has pointers, it could be easily sorted out with passing the two two int params in as pointers and a NULL would indicate that the function should ignore it. Very standard practice in both the managed and unmanaged code (for reference types). So in the case above, if the parameter values are only valid if they are non-negative, then they should be unsigned in the first place. If it were, then how in the world would we indicate an ‘ignore’ for the parameter?

      private void Foo(uint value1, uint value2)

      {

            // This doesn’t make sense anymore…

            // How now brown cow?

            if (value1 >= 0)

            {

                  DoSomething(value1);

            }

 

      }

 

This is exactly where a nullable value type is needed. And to declare one, you can just suffix a ‘?’ to the type:

      private void Foo(uint? value1, uint? value2)

      {

            // Now we is rockin’!

            // test it like this

            if (value1 != null)

            {

                  DoSomething(value1.Value);

            }

 

            // or like this

            if (value2.HasValue)

            {

                  DoSomething(value2.Value);

            }

 

      }

 

Now you can do this kind of null testing on non-reference types with this. Awesome!

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s