Type Casting in C#When the variable of one data type is changed to another data type is known as the Type Casting. According to our needs, we can change the type of data. At the time of the compilation, C# is a statically-typed i.e., after the declaration of the variable, we cannot declare it again. The value of the variable cannot be assigned to another type of variable unless we implicitly change the type of the variable. Here we will take an example of the string data type. We cannot convert the string implicitly to the int. Therefore, if we declare the variable 'i' as an int, we cannot assign the string value "Hello" into it. However, we can face a situation when there is a need to copy the value of one variable into another variable or method parameter of another type. For example, we have a variable integer, and we need to pass it to a method parameter whose type is double. Or the situation can be to assign the class variable to the variable of the type of interface. These types of operations are called Type Conversion. In C#, we can perform a different kinds of conversions.
Conversion with the helper class: For the conversion of the non-compatible type like integer and System.DateTime objects or hexadecimal strings and byte arrays, we can use System.BitConversion class, System. Convert class and the Parse methods of the built-in numeric type like as int32 Parse. Implicit Conversion: We can easily understand and use the implicit conversion. Here we are going to assign the integer to the double is known as the implicit conversion because we are haven't lost any data in this conversion. To understand this conversion here, we are going to take an example. Here we have two variable integer type value1 and value2. We are going to do the sum of two integer type value and store result in the long variable. Here this will not show any error, and we do not lose any data. This type of conversion is known as implicit conversion. Example:Output: Explicit ConversionWe can do the explicit conversion by defining the method. Users will do the explicit conversion. Users will do the conversion as per their requirements. The compiler will do the execution as per our command. Now we will do this conversion by applying the following code: Example:Output: Conversion OperatorsConversion Operators have the following properties:
Now we will take an example that follows the following code. Output: Next TopicListBox Control in C# |