Code

Type Conversion

Implicit Type Conversion ( hidden )

If one type converts into another type automatically by the CLR, it’s called implicit type conversion.

int i = 786;
double d = i; // Implicit casting from int to double

int i = 57;
// automatic type conversion
long l = i;
float f = l;

char i = '0';
int d = i;

Run Demo

Explicit Type Conversion ( Cast )

Explicit conversion is required when data cannot convert from one simple-type to another automatically by the compiler, or conversion may change the value by producing an incorrect result due to the possible loss of data (narrowing conversions).

  • Casting
  • Converting
  • Parsing

Casting

() operator is used to explicitly cast one type to another by forcing compiler to make the conversion.

Some of the conversions that cannot be made implicitly:

long l = 2222;

// use () operator to convert a type explicitly
int i = (int)l; // Explicit casting from long to int

Now, try this one.

double d = 786.78;
int i = d; // Incompatible Data Type

int i = (int)d; // Explicit casting from double to int 

When we cast 786.78 into an integer, the resulting value is 786. The decimal portion is discarded after the conversion.

Another way is to use cast, like below:

double d = 786.78;
// Or
var d = 786.78;

float f = (float)d;
decimal dec = (decimal)d;

The values of f and dec will both be 786.78.

If you try to run below code, an exception of type InvalidCastException is thrown with the message ‘Unable to cast object of type ‘System.String’ to type ‘System.Int32’

object val = "12";
int i = (int)val;

Run Demo

Overflow exception control : checked, unchecked

To throw casting errors, surround the cast into pair of round brackets () and add the word checked in front as in the following code:

long l = long.MaxValue;
int i = checked((int)l); // OverflowException

Now when the code executes at run time, the program will fail because the value is too big to fit in an int.

Run Demo

long a = 9999999999;
long b = long.MaxValue;

checked
{
    int a1 = (int)a;
    int b1 = (int)b;
}

Run Demo

Prevent overflow checking:

long l = long.MaxValue;
int i = unchecked((int)l); // OverflowException suppressed

Run Demo

Converting

You can use System.Convert class to perform conversions between base types where implicit or explicit casting isn’t possible.

string val = "786";
// Conversion from string to int
int result = Convert.ToInt32(val); // Return 786 

In the following example, the second statement uses ToBoolean method to convert int to a bool value.

int val = 0;
Convert.ToBoolean(val) ; // Print False

The ToString method lets you convert value of any variable into a textual representation.

int val = 786;
string newVal = val.ToString();

Run Demo

Different type of exceptions if a value cannot be converted.

FormatException – ‘Input string was not in a correct format.’

string val = "786.78";
Convert.ToInt32(val);
 
string val = null;
Convert.ToInt32(val); // Print 0

OverflowException – ‘Value was either too large or too small for an Int32.’.

string val = "786786786786";
Convert.ToInt32(val); 

InvalidCastException – ‘Invalid cast from ‘Double’ to ‘Char.’

double val = 786.78;
Convert.ToChar(val);

Run Demo

Parsing

Parsing is used to convert string type to a primitive value type by using built-in parsers, which are included in all the data structures of the .NET framework.

string val = "786";
int parsedValue;

bool result = Int32.TryParse(val, out parsedValue); // Return True

// With Code block

if (int.TryParse(val, out parsedValue)) {...} else {...}

Run Demo

Parse method takes a string as a parameter and returns an int, if the string contains an integer value.

string val = "786";
Int32.Parse(val); // Return 786 

Different type of exceptions if a value cannot be interpreted by the parser.

FormatException – ‘Input string was not in a correct format.’

string val = "786.78";
Int32.Parse(val);

string val = "Hello";
Int32.Parse(val);

ArgumentNullException – ‘Value cannot be null.’

string val = null;
Int32.Parse(val);

OverflowException – ‘Value was either too large or too small for an Int32.’.

string val = "786786786786";
Int32.Parse(val); 

Run Demo

Pirzada Rashid

Senior .NET developer with a Master of Science in Information Technology.
Teaching is one of my passions. It gives me great joy to share my knowledge with others, and I look forward to investing more energy into it.

Add Comment

Click here to post a comment

Popular Video

82,490+ Views