Type conversation

October9, 2017
by admin

Sometimes you need to store a value from one data type variable to different data type variable. Both variables can be of the same type but with different storage capacity. This conversation is known as Type casting.

Type casting is of two types, implicit conversion, and explicit conversion.

Let’s first understand implicit conversion with an example.

Ex 1:


  // implicit conversion
  int x;
  double y;

  // assigning values to variables
  x = 50;
  y = x; // implicit conversation

  // displaying Current values
  System.Console.WriteLine(string.Format("Value of x = {0}", x));
  System.Console.WriteLine(string.Format("Value of y = {0}", y));

Output:

Value of x = 50;
Value of y = 50;

The above code example is about an implicit conversation. First, we have declared two variables, x of type integer and y of type double.

On the next line, we have assigned value 50 to variable x.

Then we have assigned x to the variable y.

Notice here that we are storing the value of the integer data type variable in a variable which has a double data type. Since double data type has more capacity than that of integer data type, this does not need any casting. Conversion of integer to double data type happened implicitly. So it is an implicit conversion.

Lets now understand explicit conversion with an example.

Ex 2:


  // explicit conversion
  int x;
  double y;

  // assigning values to variables
  y = 75.42;
  x = (int)y; // explicit conversation

  // displaying Current values
  System.Console.WriteLine(string.format("Value of x = {0}", x));
  System.Console.WriteLine(string.format("Value of y = {0}", y));

Output:

Value of x = 75;
Value of y = 75.45;

The above code example is about an explicit conversation. First, we have declared two variables, x of type integer and y of type double same as in the previous example.

On the next line, we have assigned a value 75.45 to the variable y.

After that, we have stored the value of y (double data type) to the variable x (integer data type).

Since integer data type storage capacity is less than that of the double data type, conversion can not happen implicitly. We have to prefix the right-hand side variable with targeted data type enclosed within the parenthesis. This is an explicit conversion.

After that, we have displayed the output to console window. Look at the output. Though the value of variable y (double data type) is decimal/fractional, the value of variable x (integer data type) is a whole number without fractional value. This is one of the important points when you need to consider the conversion from higher capacity data type to the lower capacity data type.

Built-in Type Conversion methods:

Along with casting C# has some built in type conversion methods for explicit conversion, such as ToChar(), ToBoolean(), ToDateTime(),ToInt(), ToFloat(), ToString().

Ex 3:


  int x = 100;
  System.Console.WriteLine("x = " + x.ToString());

C# Fundamentals