CSharp examples for Language Basics:Data Type
C# can convert between instances of compatible types.
Conversions can be either implicit or explicit:
In the following example, we implicitly convert an int to a long type which has twice the bitwise capacity of an int and explicitly cast an int to a short type which has half the capacity of an int:
using System;/*from w ww . j a v a 2 s. c o m*/ class Test { static void Main(){ int x = 12345; // int is a 32-bit integer long y = x; // Implicit conversion to 64-bit integer short z = (short)x; // Explicit conversion to 16-bit integer Console.WriteLine (z); } }
Implicit conversions are allowed when both of the following are true: