- C# Fundamentals Tutorial
- C# - Intro
- C# - Installation
- C# - Basic Syntax
- C# - Variables
- C# - Data Types
- C# - Operators
- C# - Type Conversion
- C# - Arrays
- C# - Strings
- C# - Methods
- C# - Classes
- C# - If..Else
- C# - Loops
- C# - Enums
- C# - Inheritance
- C# - Encapsulation
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Regular Expressions
- C# - Exception Handling
C# - Type Conversion
The type conversion allows you to convert one datatype value to another data type. It is also known as type casting in C#.
There are two type of conversions: Implicit and explicit
Implicit Conversion
Implicit conversions are performed by the compiler automatically when there is no risk of data loss. For example, converting from smaller data types to larger ones.
int numInt = 10;
double numDouble = numInt; // Implicit conversion from int to double
In above example, an int is implicitly converted to a double without any explicit casting required.
Explicit Conversion (Casting)
Explicit conversions require casting and used when there is a potential loss of data. You can explicitly cast by placing the desired type in parentheses before the variable you want to convert.
double numDouble = 10.5;
int numInt = (int)numDouble; // Explicit conversion from double to int
Here, the double value is explicitly cast to an int, and any decimal information is truncated.
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. |