.Net Implicit Casts

Casts

A cast is a conversion of data from one type to another, for example from an integer to a float.

Implicit Casts

An implicit cast is a conversion from one type to another that is automatically assumed by the compiler. Therefore, an implicit cast does not appear in the program code.

In general, implicit casts can only be made when the conversion does not result in loss of information. This means that an implicit cast cannot be performed where the value being converted must be rounded or truncated.

C# Implicit Casts

TO2
sbyte byte short ushort int uint long ulong float double decimal
FROM sbyte x x x x
byte x
char x x x
short x x x x x
ushort x x x
int x4 x4 x4 x4 x4 x4 1 1
uint x x x x x 1 1
long x x x x x x x 1 1
ulong x x x x x x x 1 1
float x x x x x x x x x3
double x x x x x x x x x x3

Notes on the Table

  1. May cause loss of precision but not magnitude.
  2. There are no implicit conversions to char.
  3. There are no implicit conversions from floating-point types to decimal.
  4. Constant expressions can be converted provided the constant expression is in range of the destination type.

VB.Net Widening Casts

TO
SByte Byte Short UShort Integer UInteger Long ULong Single Double Decimal
FROM SByte x x x x
Byte x
Short x x x x x
UShort x x x
Integer x x x x x x 1 1
UInteger x x x x x 1 1
Long x x x x x x x 1 1
ULong x x x x x x x 1 1
Decimal x x x x x x x x 1 1 x
Single x x x x x x x x x
Double x x x x x x x x x x
Char Char array String
FROM Char x
Char array x
String x x

Notes on the Tables

  1. May cause loss of precision but not magnitude.

Explicit Casts

An explicit cast requires special syntax in the source code.

Summary

C# VB.Net Data Types Restrictions Runtime Failure
CType Value and Reference Types Widening or narrowing conversion must be defined between the two data types Throws InvalidCastException
Cast Operator DirectCast Value and Reference Types One type must inherit from or implement the other Throws InvalidCastException
as TryCast1 Reference types only One type must inherit from or implement the other Returns null (C#) or Nothing (VB.Net)

Notes on the Table

  1. Later versions of VB.Net only.
Be Sociable, Share!
This entry was posted in C#, VB.Net. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *