C# Data Type Conversion

C# Code Snippets Data Type Conversion


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.


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;



Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger