In this lesson, you will learn about C# Casting, conversion functions, with examples to better understand the topic.
Type casting/conversion converts a type of data to another one, such as a number to a string, a byte to a bool, etc.
In C#, there are two forms of data type casting: Implicit Type Conversion and Explicit Type Conversion.
C# performs implicit type conversion in a type-safe mode, such as conversion from a smaller to a larger data type. In Implicit Type Conversion, variable casting is unnecessary to perform the conversion.
In an explicit type conversion, a variable casting is required. For example, converting from double to int is impossible before casting the variable, as data loss may occur.
double doubleVal = 10; int intVal = doubleVal;
The code above will not compile; the error below will occur:
Error CS0266 Cannot implicitly convert type ‘double’ to ‘int’. An explicit conversion exists (are you missing a cast?)
For this purpose, a variable cast is required.
Example
Below are the methods that C# provides to perform type conversions.
Convert a type to Boolean. Example:
bool myValue = Convert.ToBoolean("True");
Converts a type to a byte. Example:
string a = "A"; byte b = Convert.ToByte(a, 16);
Converts a type to a single Unicode character. Example:
int i = 10; char c = Convert.ToChar(i);
Converts a type to date-time structures. Example:
DateTime result = Convert.ToDateTime("11/11/2022");
Converts a floating point or integer to a decimal type. Example
decimal decimalVal = System.Convert.ToDecimal("2,345.26");
Converts a type to a double type. Example:
int val = 100; double result = Convert.ToDouble(val);
Converts a type to a 16-bit integer. Example:
short shortNumber = Convert.ToInt16(3.456);
Converts a type to a 32-bit integer. Example:
Convert.ToInt32(10.0000F);
Converts a type to a 64-bit integer. Example:
long result = Convert.ToInt32(193.834);
Converts a type to a signed byte type. Example:
byte b = Convert.ToSByte((Byte) 12);
Converts a type to a small floating-point number. Example:
float floatVal = Convert.ToSingle(false);
Converts a type to a string. Example:
int number = 20; string a = number.ToString();
Converts a type to an unsigned int type. Example:
ushort = res = Convert.ToUInt16("100");
Converts a type to an unsigned long type. Example:
uint result = Convert.ToUInt32("100");
Converts a type to an unsigned big integer. Example:
ulong result = Convert.ToUInt64('a');
This concludes the C# Casting lesson. In the next lesson, you will learn about Constants in C#.