Programs are meant to manipulate data. And these data do exist in various types.
Sometimes you need to convert one data type to another.
C# provides us around six ways of converting data from one form to another:
- Implicit Conversions.
- Data Casting.
- Using the
- Data Parsing.
1. Implicit Conversion
Implicit Conversions can be categorized into two
(a). Widening Conversions.
Widening conversions occur when a variable of one data type is assigned to a variable of another data type whose maximum capacity is larger than former data type.
This involves storing a value in a variable that is guaranteed to to hold that value.
For example saving an
int value to a
static void Main()
int numOfPeople = 999;
long totalPopulation = numOfPeople;
Console.WriteLine("numOfPeople is of data type " + numOfPeople.GetType()); Console.WriteLine("totalPopulation is of data type "+totalPopulation.GetType()); Console.Read(); } }
RESULT ```language numOfPeople is of data type System.Int32 totalPopulation is of data type System.Int64
You can see that
numOfPeopleis of type
System.Int32, which is actually
totalPopulationis of type
System.Int64which is the
(b). Narrowing Conversions
In contrast in narrowing conversions the source value cannot fit into the destination variable.
For example if you have an int value and you want to convert it into a byte variable.
Well this cannot happen implicitly, even if the value itself is small enough say even 1 to fit into the destination variable.
Let’s see an example:
int numOfPeople = 1;
byte enlightenedPeople = numOfPeople; //error won’t compile
This cannot happen in C#. We cannot implicitly narrow say an int to a byte. To continue with the narrowing conversion you have to do it explicitly.