Type conversion for predefined types

All integral types may be converted to float-point type variable.


using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 5;
        float f = i;
        Console.WriteLine(i);

        Console.WriteLine(f);

    }
}

The output:


5
5

When converting a large-size type to a small-size type you can use the implicit conversion.

The following code converts an int type variable to a long type variable.

long type is larger than the int type, so the conversion is implicit.


using System;

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

        Console.WriteLine(l);

    }
}

The double type is larger than the float type.


using System;

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

        Console.WriteLine(l);

    }
}

You have to do the explicit conversion by adding a cast during an information-may-lost conversion.

The following code convert a long type variable to an int type variable.

The information contained in the long type variable may get lost during the conversion, so a cast is needed.


using System;

class Program
{
    static void Main(string[] args)
    {
        long l = 999999999999999999L;
        int i = (int)l;
        Console.WriteLine(l);

        Console.WriteLine(i);

    }
}

The output:


999999999999999999
-1486618625
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.