TYPECASTING
DEFINITION:
Converting an expression of a given type into another type is known as type-casting.
Because C# is statically-typed at compile time, after a variable is declared, it cannot be
declared again or used to store values of another type unless that type is convertible to the
variable's type
TYPES OF TYPECASTING WITH EXAMPLES
Implicit conversions: No special syntax is required because the conversion is type
safe and no data will be lost. Examples include conversions from smaller to larger
integral types, and conversions from derived classes to base classes.
e.g.:
// Implicit conversion. num long can
// hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;
Explicit conversions (casts): Explicit conversions require a cast operator. Casting
is required when information might be lost in the conversion, or when the conversion
might not succeed for other reasons. Typical examples include numeric conversion to a
type that has less precision or a smaller range, and conversion of a base-class instance to
a derived class.
e.g.:
class Test
{
static void Main()
{
double x = 1234.7;
int a;
// Cast double to int.
a = (int)x;
[Link] (a);
}
}
// Output: 1234
User-defined conversions: User-defined conversions are performed by special
methods that you can define to enable explicit and implicit conversions between custom
types that do not have a base class–derived class relationship. For more information, see
Conversion Operators (C# Programming Guide).
e.g.:
class SampleClass
{
public static explicit operator SampleClass(int i)
{
SampleClass temp = new SampleClass();
// code to convert from int to SampleClass...
return temp;
}
Conversions with helper classes: To convert between non-compatible types, such
as integers and [Link] objects, or hexadecimal strings and byte arrays, you
can use the [Link] class, the [Link] class, and the Parse methods
of the built-in numeric types, such as [Link].
e.g.:
string input = "Hello World!";
char[] values = [Link]();
foreach (char letter in values)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = [Link]("{0:X}", value);
[Link]("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
Output:
Hexadecimal value of H is 48
Hexadecimal value of e is 65
Hexadecimal value of l is 6C
Hexadecimal value of l is 6C
Hexadecimal value of o is 6F
Hexadecimal value of is 20
Hexadecimal value of W is 57
Hexadecimal value of o is 6F
Hexadecimal value of r is 72
Hexadecimal value of l is 6C
Hexadecimal value of d is 64
Hexadecimal value of ! is 21