Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of

From the author of

Basic Conversions

Conversions allow moving the value of one variable into another. There are two types of conversions—explicit and implicit. Implicit conversions happen without intervention. Table 7 shows the legal implicit conversions for C# simple types. In addition, the integer literal 0 (zero) can be implicitly converted to an enum. There are no implicit conversions to the char type.

Table 2.7 Legal Implicit Conversions for Simple C# Types

Type

Allowable Conversions

bool

None

char

ushort, int, uint, long, ulong, float, double, decimal

sbyte

short, int, long, float, double, decimal

byte

short, ushort, int, uint, long, ulong, float, double, decimal

short

int, long, float, double, decimal

ushort

int, uint, long, ulong, float, double, decimal

int

long, float, double, decimal

uint

long, ulong, float, double, decimal

long

float, double, decimal

ulong

float, double, decimal

float

double

double

None

decimal

None


Special syntax to perform implicit conversions is unnecessary because the system will recognize them when they occur. A basic consideration about implicit conversion with simple types is whether the destination type will be big enough to hold the source type without loss of data. If not, use an explicit conversion. Any conversion not listed in Table 7 requires an explicit conversion.

An explicit conversion is necessary when there's the possibility of data loss or that an error can occur. To implement this, insert a cast operator in front of the source expression. A cast operator is simply the name of the type being converted to inside of parentheses. Here are a few examples:

byte floor = 5;
int level = floor; // implicit - no cast necessary

double maxWeight = 53.751;
float upperLimit = (float) maxWeight;
         // smaller type - cast required

ushort distance = 32768;
short milesToGo = distance;
         // error – possibility of data loss

short milesToGo = (short) distance;
         // data loss – milesToGo = -32768

Reference types and structures also can be converted. The rules for determining whether a conversion is implicit or explicit are still the same. Explicit conversions could possibly cause loss of data or generate an error, but implicit conversions won't. Conversions for reference types require methods to perform the transfer of data from one type to another. These methods use the explicit and implicit keywords to mark the method appropriately. Explicit conversions from a reference type or structure require a cast, the same as the built-in types do.

  • + Share This
  • 🔖 Save To Your Account