Type Conversion & Type Casting


Type Conversion

Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms −

Implicit type conversion − These conversions are performed by C# in a type-safe manner. For example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.

Explicit type conversion − These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.



 C# Type Conversion Methods : 


Sr.No.Methods & Description
1
ToBoolean
Converts a type to a Boolean value, where possible.
2
ToByte
Converts a type to a byte.
3
ToChar
Converts a type to a single Unicode character, where possible.
4
ToDateTime
Converts a type (integer or string type) to date-time structures.
5
ToDecimal
Converts a floating point or integer type to a decimal type.
6
ToDouble
Converts a type to a double type.
7
ToInt16
Converts a type to a 16-bit integer.
8
ToInt32
Converts a type to a 32-bit integer.
9
ToInt64
Converts a type to a 64-bit integer.
10
ToSbyte
Converts a type to a signed byte type.
11
ToSingle
Converts a type to a small floating point number.
12
ToString
Converts a type to a string.
13
ToType
Converts a type to a specified type.
14
ToUInt16
Converts a type to an unsigned int type.
15
ToUInt32
Converts a type to an unsigned long type.
16
ToUInt64
Converts a type to an unsigned big integer.




Type Casting

The meaning of Type Casting is to change one data type into another data type. Developers change data type according to their need.

Types of casting in C#
1. Implicit Conversion
2. Explicit Conversion


Implicit Conversion
Implicit Conversion is done by the compiler itself.

private void ImplicitClick_Click(object sender, EventArgs e)  
{  
    int firstValue = 25;  
    int secondValue = 26;  
    long result = firstValue + secondValue;  
    //MessageBox.Show(result.ToString());         


Explicit Conversion
Explicit Conversion is done by the users according to their need/requirement. We tell the compiler to do the conversion. 
private void btnCast_Click(object sender, EventArgs e)  
{  
    int firstName = int.Parse(txtFirstNumber.Text);  
    int secondName = int.Parse(txtSecondNumber.Text);
    MessageBox.Show((firstName + secondName).ToString());  
}