user defined casts

We can convert from one data type to another. If we convert from a higher capacity data type to lower capacity datatype, the data loss will occur and this usually goes unnoticed. Therefore, it is always recommended to perform conversion under checked {} blocked, as in the following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{  
    class Program
    {     

        static void Main(string[] args)
        {
            int I = 1212122434;

            long l = I;      // implicit
            short s;
            checked { 
            s = (short)I; // explicit            
            }
            Console.WriteLine(s);
            Console.WriteLine("int {0}", sizeof(int));
            Console.WriteLine("long {0}", sizeof(long));
            Console.WriteLine("short {0}", sizeof(short));
        }
    }

}

 

Tags:,

Add a Comment

Your email address will not be published. Required fields are marked *