Monday, May 7, 2012

Using Null Coalescing Part 1

Introduction :

This article is to explore the use of C# Null Coalescing Operator. When we can use Null Coalescing and some basic examples of using Null Coalescing.


Everyone had came across a situation so far where we would like to evaluate the string value that  if the value is null then it should be converted into the empty string or some default string value.

There are multiple ways to achieve the same thing. Here are some of the examples of evaluating Null values.

Example 1 : Make use of "if Statement" :

String myValue = newValue;

if (myValue==null)
{
     myValue = string.Empty;
}

Above example works fine but what if you would like store some default values. So the answer is quite obvious i.e. change the following line: -

myValue = string.Empty; 

with the following one : -

myValue = someDefaultValue;

Quite a nice solution!. So what is the hitch in it.

You have to write the repetitive code everywhere you would like to evaluate null and set  someDefaultValues

You must be thinking why? Why to write repetitive code? we can include above if statement in a method and call that method whenever you wants to set someDefaultValues, if it is null.
Good! then lets go for it.


public string convertNullToDefaultValue(string myValue)
{
    if (myValue==null)
   {
        return someDefaultValue;
   }
  else
  {
        return myValue;
  }
}

So we did it. What else remains here? Nothing. Think for a while. What if myValue contain whitespace.Yes it will return string with white spaces only.

So we need some more modification in above method. Here it is : -

(will work only in .net 4.0)

public string convertNullToDefaultValue(string myValue)
{
    if (string.IsNullOrWhiteSpace(myValue))
   {
        return someDefaultValue;
   }
  {
        return myValue;
  }
}


(for those using less then .net 4.0)
public string convertNullToDefaultValue(string myValue)
{
    if (string.IsNullOrEmpty(myValue))
   {
        return someDefaultValue;
   }
   else
  {
        if(myValue.Trim()==string.Empty) 
       {
            return someDefaultValue;
       }
  }
}


Above method works fine, but see what we got, two different versions and couple of "if statements" .
Not a very great solution!

Think again is this what we need? Nope obviously!

Bad coding practice indeed! So which is another method to do the same. See - Using Null Coalescing Part 2



No comments:

Post a Comment