Data Type Conversions - CSharp Language Basics

CSharp examples for Language Basics:Data Type

Introduction

C# can convert between instances of compatible types.

Conversions can be either implicit or explicit:

  • implicit conversions happen automatically, and
  • explicit conversions require a cast.

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:

Demo Code

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);
   }
}

Result

Implicit conversions are allowed when both of the following are true:

  • The compiler can guarantee they will always succeed.
  • No information is lost in conversion.
  • The compiler cannot guarantee they will always succeed.
  • Information may be lost during conversion.

Related Tutorials