Type Conversion Or Type Casting In C# With Examples

10:55
We have already seen C# is strictly type language. As I have explained earlier it do not convert one type to another type that directly. There are specific ways of doing so. This procedure is called type conversion. We will see type conversion in c# with examples so you will get better understanding.

Refer to this: C# Data Type In Detail


In programming programmer need to sometime manipulate variables or convert one type to another type. For doing this process of converting one type to another is called Type conversion or type casting. There are 2 types of type conversion:

Implicit Type Conversion:
Implicit type conversion perform by system automatically you don’t have to do anything. You just assign one variable to another variable type and other all things will be taken care C# compiler. Lets see an example:


using System;
namespace TypeConversion
{
   class ImplicitConversion
   {
      static void Main(string[] args)
      {
     
         float f = 75.12546f;
         double d = f;
        
         Console.WriteLine("This is float value :"+f);
         Console.WriteLine("This is double value :"+d);
         Console.WriteLine("This is double value type converted to string type"+d.ToString());
         Console.ReadKey();
           
      }
   }
}

Here is the output of the program:

Executing the program....
This is float value :75.12546
This is double value :75.1254577636719
This is double value type converted to string type75.1254577636719

In above example compiler converted float type to double type automatically. You can also see we have used .ToString() method to print the double value. Since string is alphanumeric and larger than Double type it can accept almost all type. But it was reverse then it will give you error.

Explicit Type Conversion:
As name suggest you have to explicitly tell compiler to convert one value type to another value type. You can do it by 2 ways. Let’s see an example for the same:


using System;
namespace TypeConversion
{
   class ExplicitConversion
   {
      static void Main(string[] args)
      {
         int i = 75;
         float f = 53.005f;
         int convert=(int)f;
         double d = 2345.7652155478;
         float convertftod=(float)d;

         Console.WriteLine("This is integer value "+i);
         Console.WriteLine("This is Float value "+f);
         Console.WriteLine("Converted float to int "+convert);
         Console.WriteLine("This is double value "+d);
         Console.WriteLine("Converted doule to float "+convertftod);
         Console.ReadKey();
           
      }
   }
}


The output if this program is :

Executing the program....

This is integer value 75
This is Float value 53.005
Converted float to int 53
This is double value 2345.7652155478
Converted doule to float 2345.765

Here int is smaller type then float. Hence to convert the float into integer type we have exclusively instructed the complier by (int). By this compiler forcefully convert float type to int. As you can see .005 values has been truncated y compiler since integer type do not support precision values. Similarly the case with double converted to float. You can see only first 3 values after precision have been taken and value hereafter has been truncated. Since compiler converting larger type to smaller type there is always some values that loss during conversion.

Now we move on to most important part that actually useful in real life:
We are going to see how to take user input in program and manipulate it then show it as display output.
We are going to take following thing from user as input:
First Name
Last Name
Salary
Age
Self-Description
And display user his info as output.


using System;
namespace UserInputApplication
{
   class UserInput
   {
      static void Main(string[] args)
      {
          //Defining Variable
         string fName,lName,describtion;
         int age;
         double sal;
        
         //When user input the value it will initialized
         Console.writeLine(“Enter Your First Name :\n”);
         fName=Console.ReadLine();
         Console.writeLine(“Enter Your Last Name :\n”);
         lName=Console.ReadLine();
         Console.writeLine(“Tell us something about you :\n”);
         describtion=Console.ReadLine();
         Console.writeLine(“Enter Your Age:\n”);
         age=Convert.ToInt32(Console.ReadLine());
         Console.writeLine(“Enter Your Salary :\n”);
         sal=Convert.ToDouble(Console.ReadLine());
        
         Console.WriteLine("Hello"+fName+" "+lName+"nice to know you. You age is "+age+" All we know about you is "+describtion+"And your salary is "+sal);
         Console.ReadKey();
      }
   }
}


Output of this program is:

Enter Your First Name :
Dharmesh
Enter Your Last Name :
Khatri
Tell us something about you :
I am programmer and blogger
Enter Your Age:
24
Enter Your Salary :
20000

You must have noticed for accepting first name and last name and description we just assign value to variable. While accepting age and Salary we need to convert to int and float type. Why is that so? Is it necessary? The answer is as follows:
When Console.ReadLine() method accept data from the user it will by default accept the data as String format. So assigning String type to string, there is no need of conversion. But while assigning string to integer or float will be problem. Hence we have to convert it into respective data types.
Here are list of methods that can used for Type Conversion:

ToBoolean()
ToByte()
ToChar()
ToDateTime()
ToDecimal()
ToDouble()
ToInt16()
ToInt32()
ToInt64()
ToSbyte()
ToSingle() //Converts a type to a small floating point number.
ToString()
ToUInt16()
ToUInt32()
ToUInt64()

The names itself are self-explanatory of converting methods. You can check yourself by using them as we have used in above program.

So here we have seen all implicit type conversion explicit type conversion user type conversion with an example. If you have any query comment below. Thanks for reading stay tuned for more.

Share this

CEO and Admin of TechnoDiscover And Nothing Like Everything
Bcom From Mumbai University
Pursuing MCA From Mumbai University

Related Posts

Previous
Next Post »