null coalescing operator
In this article I will give a brief example of how to work with null coalescing operator and how effectively we can use it.We always write conditions in the C# language to verify the variable against the null check as following
You can read about more C# related articles here.
public class MyClass { public string localVar; public string ReturnValue() { if(localVar != null) { return localVar; } else { return "localVar was null"; } } }
Now suppose if I want to use the instance of this class as shown below, the output is “Test”
MyClass inst = new MyClass(); inst.localVar = "Test"; Console.WriteLine(inst.ReturnValue()); //output is "Test" Console.Read();
But if we want to use the same instance of the class without assigning the localVars value as shown below, the output is “localVar was null”
MyClass inst = new MyClass(); Console.WriteLine(inst.ReturnValue()); //output is "localVar was null" Console.Read();
In place of writing and using the whole if-else condition we can simply shorten the above code using the null coalescing operator as shown below
public string ReturnValue() { return localVar ?? "localVar was null"; }
Here we can say that null coalescing operator is syntactic shortcut for comparing and assigning the reference types against null.
Using null coalescing operator with value types
As shown in the above example we have used the null coalescing operator with a reference type(string), but it is not the same case with value types as it will show as compile time error.
But we can use the operator with nullable value type as shown in the below example.
public class MyClass { public int? localInt; public int UsingWithValueType() { return localInt ?? 1; } }
Chaining the null coalescing operator
We can apply the null coalescing operator to the number of variables as shown below.
public string ReturnValue(string param) { return localVar ?? param ?? "neither localVar not param is paased"; }
Here in this case if the value of localvar is null then param’s value is returned and if both are null in that case “neither localVar not param is paased” is returned.
The above code example in absence of the null coalescing would be as following
public string ReturnValue(string param) { return localVar == null ? (param ==null ? "neither localVar not param is paased" : param) : localVar ; }
which is bit clumsy to write
It also works well if null-possible object isn’t a variable:
string anybody = Parameters["Name"] ?? Settings["Name"] ?? GlobalSetting["Name"];
Leave a Reply