In this post we will discuss
Implicit Conversions
Explicit Conversions
Parse() and TryParse()
Type conversion is a mechanism to convert one datatype to another.Conversion is based on type compatibility and data compatibility.
Implicit Conversion :
Implicit conversion is done automatically by the compiler:
1. When there is no loss of information if the conversion is done
2. If there is no possibility of throwing exceptions during the conversion
It includes conversion of smaller datatype to larger datatype ,conversion of derived class to base class. This is a safe type conversion.
Example
using System;
namespace ImplicitConversion {
class Program {
static void Main(string[] args) {
int i = 100;
// float is bigger datatype than int. So, no loss of
// data and exceptions. Hence implicit conversion
float f = i;
Console.WriteLine(f);
}
}
}
Explicit Conversion:
Output :
Explicit conversion is being done by using a cast operator.
It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion.
Example
using System;
namespace ExplicitConversion {
class Program {
static void Main(string[] args) {
float f = 100.25 F;
// Use explicit conversion using cast () operator
int i = (int) f;
// OR use Convert class
// int i = Convert.ToInt32(f);
Console.WriteLine(i);
}
}
}
Output :100
If a number is string we can’t convert to int then we use Parse and TryParse.
Difference between Parse and TryParse :
1. If the number is in a string format you have 2 options - Parse() and TryParse().
2. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.
3. Use Parse() if you are sure the value will be valid, otherwise use TryParse().
Program using Parse()
using System;
namespace arrays {
class Program {
static void Main(string[] args) {
string value = "200t";
int enternumber = int.Parse(value);
Console.WriteLine(enternumber);
}
}
}
Output : throws an exception FormatException was unhandled.
Then we can use TryParse. TryParse does not cannot throws an exception.
Program using TryParse()
Program using TryParse()
using System;
namespace arrays {
class Program {
static void Main(string[] args) {
string value = "200t";
int r;
bool enternumber = int.TryParse(value, out r);
Console.WriteLine(enternumber);
}
}
}
Output :
| TryParse() Example |