Type casting in C# is the process of converting a value from one data type to another. It allows you to explicitly convert a value to a different type or handle compatibility between different types. Here's an explanation of type casting in C#:
1.
Implicit Casting:
v Implicit
casting, also known as widening conversion, occurs when a value of a smaller or
narrower data type is assigned to a variable of a larger or wider data type.
v It
happens automatically without any explicit conversion or data loss.
v Example:
int num = 10;
double decimalNum = num; //
Implicit casting from int to double
2.
Explicit Casting:
v Explicit
casting, also known as narrowing conversion, occurs when a value of a larger or
wider data type is assigned to a variable of a smaller or narrower data type.
v It
requires an explicit cast operator or conversion method to perform the conversion.
v Explicit
casting may result in data loss or potential runtime errors if the value being
casted is outside the range of the target type.
v Example:
double decimalNum = 3.14;
int num = (int)decimalNum; //
Explicit casting from double to int
3.
Conversion Methods:
v In
addition to explicit casting using the cast operator `(type)`, C# provides
several built-in conversion methods to convert between compatible types.
v The
`Convert` class provides methods like `ToInt32`, `ToDouble`, `ToString`, etc.,
to convert values to different types.
v Example:
string strNum = "42";
int num = Convert.ToInt32(strNum);
// Using Convert.ToInt32 method for casting
4.
Checking for Type Compatibility:
v Before
performing a type cast, you can use the `is` operator to check if a value is
compatible with a specific type.
v The
`is` operator returns a boolean value indicating whether the cast is possible
or not.
v Example:
object obj = "Hello";
if (obj is string)
{
string str = (string)obj; //
Explicit casting after checking compatibility
Console.WriteLine(str);
}
5.
Handling Invalid Casts:
v If
an invalid cast is attempted, it will result in an `InvalidCastException` at
runtime.
v To
handle potential invalid casts, you can use the `as` operator or the `TryParse`
method (available for certain types) to perform a cast and return `null` or
`false` if the cast is not possible.
v Example
using `as` operator:
object obj = "Hello";
string str = obj as string; //
Casting with the 'as' operator
if (str != null)
{
Console.WriteLine(str);
}
Type casting is useful when you need to convert values between different data types or when you want to ensure compatibility between types. It allows you to handle data in a more flexible and controlled manner in your C# programs.
0 Comments