Skip to main content

C# -Type Conversion

Type Conversion means to Convert one data type to another. Generally type conversion is done in two form
  1. Implicit Type Conversion : In This type of conversion the conversion is done automatically by the compiler, from smaller data type to larger data type or from derived classes to base class
  2. Explicit Type Conversion: In This type of conversion the conversion is done automatically by the compiler, from smaller data type to larger data type or from derived classes to base class
Implicit Type Conversion Example:

1
2
3
4
int i_num;
 i_num = 78;
 double d_num;
 d_num = i_num; // Implicit Conversion

Explicit Type Conversion Example :

1
2
3
4
int i_num;
double d_num;
d_num = 78.45;
i_num = (int)d_num; //Explicity Type Conversion

C# provide three difference ways for data type conversion
  1. Type Cast Operator () 
  2. Convert Class
  3. Paring
Type Cast operation we have used in the above example. The second is Convert Class  which has different methods.

Method Description
ToBoolean Converts a type to a Boolean value, where possible.
ToByte Converts a type to a byte.
ToChar Converts a type to a single Unicode character, where possible.
ToDecimal Converts a floating point or integer type to a decimal type.
ToDouble Converts a type to a double type.
ToInt32Converts a type to a 32-bit integer.
ToInt16Converts a type to a 16-bit integer.
ToInt64Converts a type to a 64-bit integer.
ToStringConverts a type to a string.

The following example converts various value types to string type −

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;

namespace TypeConversionApplication {
   class StringConversion {
      static void Main(string[] args) {
         int i = 75;
         float f = 53.005f;
         double d = 2345.7652;
         bool b = true;

         Console.WriteLine(i.ToString());
         Console.WriteLine(f.ToString());
         Console.WriteLine(d.ToString());
         Console.WriteLine(b.ToString());
         Console.ReadKey();
            
      }
   }
}

When the above code is compiled and executed, it produces the following result
75
53.005
2345.7652
True

Comments

Popular posts from this blog

How to debug or execute C# program in Visual Studio?

Using Visual Studio 2005/2008/2012/2013 or any version Visual Studio is easiest way to handle C# code. To execute the program on visual studio, go through the following steps: Step 1: Launch Visual Studio and go to File > New Project Step 2: Select Visual C# in left pane and then choose Console Application. Name your Project and select Location and ok Step 3: Visual Studio will open a code editor window including some necessary code. Step 5: Now write now Write in Main method the following line of code  code and press F5 to run C# code. Console.WriteLine("Hello Welcome to ChashLearner"); Step 6: You will see the  output in Visual Studio Command Prompt.