Data type conversion

The variable's type is convertable between compatible types.

There are two types of conversion: implicit and explicit.

Implicit conversion doesn't require a cast, while the expilcit needs a cast.

In the following code we implicit convert an int type variable to long type.


using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 5;
        long l = i;

        Console.WriteLine("i=" + i);
        Console.WriteLine("l=" + l);
    }
}

The output:


i=5
i=5

Here the conversion is implicit since the long type variable can hold larger value than an int type variable.

The information in int type isn't lost during the conversion.

The following code shows an expilcit conversion.


using System;

class Program
{
    static void Main(string[] args)
    {
        long l = 9999999999999999L;
        int i = (int)l;

        Console.WriteLine("i=" + i);
        Console.WriteLine("l=" + l);
    }
}

The output:


i=1874919423
l=9999999999999999

The code above uses a cast (int) to convert long type variable to an int type variable.

A cast is done by placing (int) in front of the variable l.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.