Wednesday, August 3, 2011

Different Ways of using the C# Null Coalescing Operator


The C# Null-Coalescing operator or the ?? operator is a binary operator that returns the left-hand operand if it is not null; otherwise it returns the right operand. It can be used with both nullable and reference types.
Here’s a simple example of using the Null-Coalescing operator
int? i = null;
int j = i ?? 2;
// here the resultant value of j is 2
Here are some additional ways of using the Null-Coalescing operator in your code.

Method 1
string address = homeAddress1 ?? homeAddress2 ?? officeAddress
                 ??  "No Address";
returns the first non-null value in this long expression. This expression returns “No Address” if homeAddress1, homeAddress2 and officeAddress are Null.


Method 2
While converting a Nullable Type to Non-Nullable type, we do an explicit cast to avoid assigning null values to a non-nullable type, as shown below:
int? a = NullType(); // returns nullable int
int b = (int)a;
instead you can avoid the explicit cast using a null-coalescing operator and write:
int? a = NullType();
int b = a ?? 0;

Method 3
private IList person;
public IList PersonList
{
    get
    {
        return person ?? (person = new List());
    }
}
Typical usage of the null-coalescing operator in a lazy instantiated private variable.


Method 4

string conn = Connection["TestMachineStr1"]
            ?? AppConnection["ProdMachineStr2"]
            ?? DefaultConnection["DefaultConn"];
Accessing NameValueCollections and choosing the first non-null value.

Note: The Null-Coalescing operator is useful but may sometimes be an overkill, especially when developers use it to flaunt their coding skills. I sometimes choose ‘understandable code’ over ‘terse code’, focusing on the intent.

C# Null Coalescing Operator and its Uses


The C# Null Coalescing Operator (??)  is a binary operator that simplifies checking for null values. It can be used with both nullable types and reference types. It is represented as x ?? y which means if x is non-null, evaluate to x; otherwise, y. In the syntax x ?? y
  • x is the first operand which is a variable of a nullable type.
  • y is the second operand which has a non-nullable value of the same type.
While executing code, if x evaluates to null, y is returned as the value. Also remember that the null coalescing operator (??) is right-associative which means it is evaluated from right to left. So if you have an expression of the form x ?? y ?? z, this expression is evaluated as x?? (y?? z).
Note: Other right-associative operators are assignment operators, lambda and conditional operators.
Now with an overview of the C# Null Coalescing operator, let us see how to use the Null coalescing operators in practical scenarios.

Scenario 1 – Assign a Nullable type to Non-Nullable Type

Consider the following piece of code where we are assigning a nullable type to a non-nullable type.
C# Nullable Type
In the code above, if the nullable type (in our case ‘a’) has a null value and the null value is assigned to a non-nullable type (in our case ‘b’), an exception of type InvalidOperationException is thrown, as shown below:
image
One way to resolve this error is to use a IF..ELSE condition and check the value of the nullable type before assigning it to the non-nullable type
C# Nullable to Non-nullable
The code will now compile and give you desired results. However using the null coalescing operator in such scenarios, you can create clearer code than the equivalent if-else statement, as shown below:
image
In the code shown above, if ‘a’ has been assigned a non-null value, then this value will be assigned to the int b. However since the nullable type ‘a’ has been assigned null, the value to the right of the operator (??) i.e. zero will be assigned to b instead.
The value of b if printed, is 0.

Scenario 2 – Initializing instance fields in a Struct

You cannot declare instance field initializers in a Struct. The following piece of code:
image
gives a compilation error: cannot have instance field initializers in structs 
However using the Null coalescing operator, you can use a work-around as follows:
Struct Field Initializer
The value A can now be accessed and will return 1. Quite a handy technique using the Nullable type and the Null Coalescing operator!

Wednesday, February 16, 2011

What is the difference between exception and error

An Exception can be caught and recovered:
Any error or problem which one can handle and continue to work normally. Exception can be guessed and can be handled. 
 ArrayIndexOutOfBoundsException means you tried to access a position of an Array that does not exist . 
 
An Error is unrecoverable: OutOfMemoryError means that the JVM has no more memory to continue.

Error: Any departure from the expected behavior of the system or program which stops the working of the system is an error. In general error is which nobody can control or guess when it occurs.

Note that  a compile time error is normally called an "error " while a runtime error is called an "exception."