Monday, May 7, 2012

Using Null Coalescing Part 3

Example 3: Make use of "null coalescing" :

Finally, we can make use of null coalescing operator (??). Here is an example of it: -

string myValue = newValue ?? someDefaultValue

Oh! is that so simple!....yes it is. But if newValue contains white-spaces then what? It will return white-spaces. So lets put it altogether in the method to return null if string contains white-spaces.

(for those using less then .net 4.0)
public  string evaluateNullOrWhiteSpace(string valueToEvaluate)
{
     if (string.IsNullOrEmpty(valueToEvaluate))
     {
         return null;
     }
    else
    {
         return (myValue.Trim()==string.Empty) ? null : valueToEvaluate)
    }

}

(for those using less then .net 4.0)
public string convertNullToDefaultValue(string myValue)
{
    if (string.IsNullOrWhiteSpace(myValue))
   {
        return null;
   }
  {
        return myValue;
  }
}

Call the above method using the magic of null coalescing : -

string myValue = evaluateNullOrWhiteSpace(newValue) ?? someDefaultValue

This is now you can set the default value for completely empty string (including white-spaces only).


No comments:

Post a Comment