Tuesday, August 20, 2013

C# - Implicit casting VS Explicit Casting

Implicit casting
The implicit cast occurs automatically because we don’t lose any data while making the cast. 

Example:
In this example, we create an implicit cast from Integer to double, double can store all values that an integer can support, therefore we doesn’t have any loss of information.

class Program
    {
        static void Main(string[] args)
        {
            int a = 10;

            double b = a; //cast         
        }
    }
Explicit casting
When using this cast, we have loss of data, therefore we must tell the compiler that we know and allow this lost.

Not like the implicit casting, in explicit casting we need to use specific syntax that tell the compiler that we allow the loss of data while creating the cast.

Example:

As you can see, we create cast from double that host value that integer value cannot initialize with, therefore we lose data (Original value 5.8 after cast 5).

class Program
    {
        static void Main(string[] args)
        {
            double a =5.8;
            int b = a; //The cast will failed
            b = Convert.ToInt32(a);//Success 

        }
    }

2 comments:

  1. Hi David,

    You have a mistake in the second example, the data type for a should be double and the value 5.8, and the data type for b should be int.

    ReplyDelete
  2. 10X for this comment, I already fixed this issue.
    I hope to receive more comments from you…

    ReplyDelete

My Presentations