Tuesday, November 12, 2013

3 Lesser-Known .Net Language Features, in C#

Overview

By the time you're done reading this post you're going to see more question marks than Jim Carrey wore in that God-awful batman movie. Ugh, comedians in tights. Anyways, on to the post. We're going to talk about 3 handy little gems, the conditional operator (?:), nullable types, and the null-coalescing operator (??).

 

Conditional Operator (?:)

I'm a big fan of writing the least amount of code required to get the job done. Partly due to laziness true (I know you were thinking it), but also because the less code that exists now, the less code has to be maintained in the future. Every bit helps. How does the conditional operator work? Let's look at an example:

if (anotherObject.BoolProperty) 
    myObject.StringProperty =  "Bob";
else
    myObject.StringProperty = "Fred";

Here we are setting the value of myObject.StringProperty to either "Bob" or "Fred" depending on the value of anotherObject.BoolProperty, a boolean field. This takes 4 lines of code. We can make this more succinct without losing any meaning or readability through usage of the conditional operator, as follows:

myObject.StringProperty = anotherObject.BoolProperty ? "Bob" : "Fred";

Easy neh? 4 lines of code is now a single line of code.

Nullable Types (?)

Nullable types are pretty cool. In .Net classes you frequently have properties that are basic value types such as integers, booleans, doubles, etc. As you probably know these types cannot be assigned a null value. Well with nullable types you can indeed assign null to these primitives. This might seem like a bit of a niche coding feature, but it really can be quite useful. Take for example an import of data from another system. If your object structure doesn't precisely match the source material, perhaps you want to be able to tell in your destination object structure which fields had a value set from the import process and which did not. If you have a boolean field in your destination object structure, but the import file does not contain this field, can you tell by looking at your object after the fact whether the value was set or not? Normally no you cannot, because the boolean property has only true/false values. However if it's a nullable boolean, a null value could easily be used to represent a lack of information from the import file. OK it's time for an example:

     public class Class1
    {
        public Nullable<int> AnInt { get; set; }
    }

    public class Class2
    {
        public Class2()
        {
            Class1 localObj = new Class1();
            localObj.AnInt = null;
        }
    }

Note the highlighted lines? We can set our property to a null value because it's a nullable type. There's a slightly shorter version of the same property definition as per the below:

public int? AnInt { get; set; }

This code has the exact same meaning as before, it just has fewer characters.

Null-Coalescing Operator (??)

I like to use the null-coalescing operator in conjunction with nullable types. The null-coalescing operator will return the left-hand operator if it is non-null, otherwise it returns the right-hand operator. Let's see another example:

    public class Class1
    {
        public string AString { get; set; }
    }

    public class Class2
    {
        public Class2()
        {
            Class1 localObj = new Class1();
            string localString = null;
            localObj.AString = localString ?? localObj.AString;
        }
    }


The highlighted line is once again the interesting one. Here we are telling the compiler to set localObj.AString to the value localString, unless localString is null (which it is) then localObj.AString gets assigned back to itself, and we did it with a single line of legible code!

Wrapping It Up

I hope you enjoyed this post and are excited to experiment with the above 3 simple yet extremely useful features of the .Net runtime. Drop me a line if you have questions or comments!

Resources



No comments:

Post a Comment