Saturday 1 August 2015

Implicit vs Explicit Conversion

Implicit conversation, refers to the automatic conversion of one data type to another without the use of explicit casting. For example if you're casting from a short (16 bit) to an int (32 bit) since short has fewer bits allocated to it than an int, you know for certain that the short will fit into the int and now explicit cast is required.

When it comes to the other way around, when you try to fit an int into a short it's a different story. If the value of the int is greater than what the short can store you're in for some surprises, but we'll talk about those later.


namespace pc.converstion
{
    class Program
    {
        static void Main(string[] args)
        {
            //Narrowing Conversion requires Explicit cast
            int myInt = 133;
            short myShort = (short)myInt;

            //Widening Conversion may have an implicit cast
            short myShort2 = 34;
            int myInt2 = myShort2;

            //but there's nothing wrong with having an Explicit cast
            int myInt3 = (int)myShort2;

            //event though a bool should fit into a short or int,
            //explircity or implicity this is not allowed
            bool myBool = true;
            short failedExplicit = (short)myBool;
            short failedImplicit = myBool;

            //a workaround is cast 1 or 0 as a short or byte
            short workaround = myBool ? (short)1 : (byte)0;

            //works just as expected.  
            int workaround2 = myBool ? 1 : 0;
        }
    }
}


In conclusion if you're converting from a smaller value type to a larger one you shouldn't have any issues; except for bool's, bool's can't be cast implicitly or explicitly to other value types. I mention this because in javascript and other languages, true is synonymous with 1 and false with 0. 

however a reasonable workaround is to assign 1 if your boolean value is true and 0 if it is false, remember that there is no literal suffix for shorts or bytes, meaning that you have to explicitly cast your numeric values to them.

In short both explicit and implicit conversation can be used for data type conversion in C#, but explicit conversation is generally used when there is a potential for data loss during the conversion, while implicit conversation is used when there is no risk of data loss.