C# type conversion
Type conversion is fundamentally type casting, or the conversion of data from one type to another. In C#, there are two forms of type casting:
Implicit type conversions-these conversions are the default conversions of C# in a secure manner and do not result in data loss. For example, convert from a small integer type to a large integer type, and from a derived class to a base class.
Explicit type conversions-explicit type conversions, conversion requires a cast operator, and a cast can result in data loss.
The following example shows an explicit type conversion:
Example
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;
// Cast double to int
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
5673
C# type conversion method
C# provides the following built-in type conversion methods:
The following example converts types of different values to string types:
Example
namespace TypeConversionApplication
{
class StringConversion
{
static void Main(string[] args)
{
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
75
53.005
2345.7652
True