Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

C# Type Conversions



Conversion is the process of changing the value of one Type to another. System.Convert class provides a complete set of methods for supported conversions.
In CSharp type conversions are divided into two, Implicit Conversions and Explicit Conversions. Conversions declared as implicit occur automatically when required and Conversions declared as explicit require a cast to be called.

1:int ctr = 999;
2:long count = ctr;
// implicit conversion from int type to long type

From the above statements, the first line declares an integer type variable ctr and assigned 999 to it. The second line declares a long type variable count and assigns the value of ctr to count. Here the conversion occurred automatically. Because we converted an integer type to long type, this type of conversion is called Implicit Conversion.

1:int ctr = 999;
2:long count = ctr;
// implicit conversion from int type to long type
3:int cnt = (int)count;
// explicit conversion from long type to int type

We already saw the Implicit Conversion happened in the second line. The third line again, we converted long type to an integer type. Here we explicitly convert long type to integer (int cnt = (int)count). Otherwise, the compiler will show compiler error – Error 1 Cannot implicitly convert type ‘long’ to ‘int’. An explicit conversion exists (are you missing a cast?) . This type of conversion is called Explicit Conversion.
The following C# source code shows how to use System.Convert class.

using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string str = "true";
                bool flag = System.Convert.ToBoolean(str);
                MessageBox.Show("flg value is " + flag);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot conver the value" + ex.ToString() );
            }
        }
    }
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More