Home »
.Net
Explain Type Conversion in C#
Learn: What are the type conversions in C#.Net, types of type conversions and how they can be used to convert one data type’s value to another in C#.
Type conversion is a basic and important feature of almost all programming languages, Type conversion is used to convert one type of data into another type. It is also known as type casting.
There are two type of type casting/conversions used in c#:
- Implicit or automatic type casting
- Explicit type casting
1) Implicit or automatic type casting
Implicit type casting is performed in type safe manner in c#. When we convert data from smaller to larger integral type and conversion from child class to parent class in known as implicit type conversion.
2) Explicit type conversion
This conversion is not performed automatically. For explicit type conversions we need to use pre-define functions. Sometime we need to use some conversion operators.
Consider the program:
using System;
class Sample
{
static void Main(string[] args)
{
double var1 = 3.245;
int var2 = 0 ;
//Convert double to int
var2 = (int)var1;
Console.WriteLine(var2);
}
}
Output
3
After compiling and executing above program the result will be 3.
In above program var1 variable is double type but we are converting its value to int and assigning to var2.