Converting data from one type to another

In C# a special class has been created to convert data types from one type to another. For example if you have a string “12345” and you want to convert it to an integer value 12345 or if you have string “1.5” and you want to convert it to a double then you can make use of this class.

The Convert class

This class used for converting inputs from one type to another is called the Convert class. It has many static methods like ToString, ToInt32, ToInt16, ToInt64, ToDouble etc which can be used for conversions. The names of the methods are self explanatory here.

Converting a string to Integer

Look at the program below

static void Main(string[] args)  {          string str = "12345";            int number = Convert.ToInt32(str);          int sum = 1 + number;            Console.Write("The total is : " + sum);  }

Here we have string variable with value “12345”. The double quotes tell us that it is a string. In this program we are converting this value to an integer type by using the Convert.ToInt32 method. Now that it becomes an integer type value we can use it for performing integer operations like Sum. So here we are adding 1 to this number and printing the output. This is the output we get

Convert class in C#
 
Similarly you can use the other methods of the Convert class as per your needs.

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp