Monday, February 24, 2014

System.Nullable?

System.Nullable?

Supported from C# 2.0.

Consider you have a database with a column for age. You are picking items from the DB and assigning it to a local class value (Employee), which has a property (Age - int). Now if this value is empty in any record, you will get a compiler exception during compilation of the project.

Error will be, 'Cannot convert null to 'int' because it is a non-nullable value type'. So you cannot assign a null value to int. For that comes in to picture is the Nullable.

            int? age = null; //This will compile fine.
            System.Nullable<int> age = null; //Both are same.

Here you need to think about two points.

* Value should always be accessed as age.Value.
int t = k1; //This will give an error. Reason is int? is different from int.

* You should use age.HasValue (boolean) to confirm whether this has any value. If you are directly taking the value and that is going to be a null, you will get an 'Invalid Operation' exception.

This is fairly proper.

            int? age = null; //Supported
            int t;
            if (age.HasValue) //Without this Invalid Operation will be thrown.
            {
                t = age.Value;
            }
Result --> t = 0.

            int? age = 10;
            int t;
            if (age.HasValue)
            {
                t = age.Value;
            }
Result --> t = 10.

No comments:

Post a Comment

Followers