Tutorials Navigation

Tutorials :: New :: Popular :: Top Rated

Tutorials: 18,326 Categories: 12

Total Tutorial Views: 41,403,492

C# - Type Conversion

Tutorial Name: C# - Type Conversion  

Category: PC Tutorials

Submitted By: Nissan

Date Added:

Comments: 2

Views: 645

Related Forum: PC Building Forum

Share:

C# - Type Conversion


Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms:

Implicit type conversion - These conversions are performed by C# in a type-safe manner. For example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.

Explicit type conversion - These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.

The following example shows an explicit type conversion:


using System;
namespace TypeConversionApplication
{
   class ExplicitConversion
   {
      static void Main(string[] args)
      {
         double d = 5673.74;
         int i;
         
         // cast double to int.
         i = (int)d;
         Console.WriteLine(i);
         Console.ReadKey();
      }
   }
}


When the above code is compiled and executed, it produces the following result:

5673


C# Type Conversion Methods

C# provides the following built-in type conversion methods:

[ Register or Signin to view external links. ]

The following example converts various value types to string type:


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

Ratings

Current rating: 10.00 by 3 users
Please take one second and rate this tutorial...

Not a Chance
1
2
3
4
5
6
7
8
9
10
Absolutely

Comments

"C# - Type Conversion" :: Login/Create an Account :: 2 comments

If you would like to post a comment please signin to your account or register for an account.

MickersPosted:

Had to do this recently.

Rather easy using this.

HaloPosted:

Even though you made this somewhat easy to understand it still seems like a lot.