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.

Difference between var and dynamic in C#

dynamic - dynamically typed.

Example 1:
            dynamic di; //this code is valid.
            di = "MKS"; //this code is valid.
            di = 10; //this code is valid. Compiler will dynamically assign the type.

Example 2:
            dynamic di; //this code is valid.
            di = "MKS"; //this code is valid.
            di++; //During runtime, this will throw an exception. Until this step and until running the code, compiler will not know that di is a string.

Use of dynamic is mostly helpful during the com components usage in C#. Mainly, when you are accessing the Excel (or any Office) objects using VSTO, you can use this flexibly with Excel objects avoiding type casting.

var - implicit but statically typed.

Example 1:
            var d; //this is wrong. You should be giving some values to hint the compiler that d is of this type.

Example 2:
            var d1 = 10; //this is valid.
            d1 = "MKS";//This is invalid and it will fail during compile time itself. Because d1 is fixed to be an integer during the initial assignation. The message will be, 'cannot implicitly convert type string to int'.

Reference:
http://stackoverflow.com/questions/961581/whats-the-difference-between-dynamicc-4-and-var

Followers