Type Casting is a process of converting the value of one data type into another data type (for example: converting a number into a string, or converting a string into a number).
The two main methods of Type Casting are:
char
-> int
-> long
-> float
-> double
double
-> float
-> long
-> int
-> char
With Implicit Casting, the conversion of the value is performed automatically whenever the value is passed from a smaller size variable type to a larger size variable type:
int myInt = 12 ;
double myDouble = myInt ; // Automatic casting of converting an int into a double
Console .WriteLine (myInt ); // outputs 12
Console .WriteLine (myDouble ); // outputs 12
With Explicit Casting, the conversion of the value is only performed whenever manually told to do so. There are two ways in which you can manually perform explicit casting:
Explicit casting using the manual method is performed by placing the desired variable type in parentheses in front of the value that you want to convert from:
double myDouble = 12.3456 ;
int myInt = (int )myDouble ; // Manual casting of converting a double into an int
Console .WriteLine (myDouble ); // outputs 12.3456
Console .WriteLine (myInt ); // outputs 12
Explicit casting using the Type Conversion methods is performed by using the built-in type conversion methods available with the System.Convert
class:
int myInt = 1 ;
double myDouble = 6.78 ;
bool myBool = true ;
string myString = "24.13" ;
Console .WriteLine (Convert .ToString (myInt )); // convert int to string
Console .WriteLine (Convert .ToDouble (myInt )); // convert int to double
Console .WriteLine (Convert .ToInt32 (myDouble )); // convert double to int
Console .WriteLine (Convert .ToString (myDouble )); // convert double to string
Console .WriteLine (Convert .ToString (myBool )); // convert bool to string
Console .WriteLine (Convert .ToInt32 (myBool )); // convert bool to int
Console .WriteLine (Convert .ToInt32 (myString )); // convert string to int
Console .WriteLine (Convert .ToDouble (myString )); // convert string to double
int myInt2 = Convert .ToInt32 (myDouble ); // convert double to int
double myDouble2 = Convert .ToDouble (myString ); // convert string to double
bool myBool2 = Convert .ToBool (myInt ); // convert int to bool
string myString2 = Convert .ToString (myDouble ); // convert double to string
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
About | Contact Us | Privacy | Terms & Conditions | © 2024 - T&J Divisions, LLC, All Rights Reserved |