About
In this code snippet, we will learn how to perform data type conversions in C#.
C# has many different data types. You might find yourself needing to convert from one data type to another. This can be done implicitly by just assigning the value of one variable to another and the conversion will happen automatically. For example, assigning a short to int can be done implicitly as short is just a smaller int. Meanwhile converting a string to an int has to be done explicitly.
Let’s take a look at a few examples in the code example below.
Code:
using System; namespace DataTypeConversion { class Program { static void Main(string[] args) { //Implicit short to int conversion. short shortVariable = 5; int intVariable1 = shortVariable; //Explicit string to int conversion. string stringVariable1 = "10"; int intVariable2 = int.Parse(stringVariable1); //Explicit int to string conversion. string stringVariable2 = intVariable2.ToString(); //Explicit int to double conversion(using casting). double doubleVariable = 1.1; //When converting double/float to an int the decimal places are lost. Not rounded up or down but just cut off. int intVariable3 = (int)doubleVariable; Console.WriteLine(intVariable1); Console.WriteLine(intVariable2); Console.WriteLine(stringVariable2); Console.WriteLine(intVariable3); Console.ReadLine(); } } }