C# Data Type – Conversions

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:

  1. Implicit Conversions.
  2. Data Casting.
  3. Using the as Operator.
  4. Data Parsing.
  5. Using System.Convert.
  6. Using System.BitConverter.

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 long varaible.

EXAMPLE
“`C#
using System;

namespace DataTypeConversions
{
class Program
{
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 numOfPeople is of type System.Int32, which is actually int while totalPopulation is of type System.Int64 which is the long.

(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:

“`c#
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.

Share



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )