C# Type Conversion

C# Type Conversation

The converting type in C# is basically type casting , you will need to convert data from one type to another. Data can be converted in two forms:



  • Implicit - these conversions between types are performed whenever the conversion can occur without the loss of data.Examples are conversions from smaller to larger integral types, and conversions from derived classes to base classes.
  • Explicit -When performing a conversion where types cannot be implicitly converted, you must explicitly convert the types. This conversion is called a cast. Explicit conversions using a special syntax in Visual C#.



      Table for Implicit conversion:


From
To
byte(Visual C#)
short, ushort, int, uint, long, ulong, float, double, decimal
short
int, long, float, double, decimal
int
long, float, double, decimal
long
float, double, decimal
float
double
sbyte
short, int, long, float, double, decimal
ushort
int, uint, long, ulong, float, double, decimal
uint
long, ulong, float, double, decimal
ulong
float, double, decimal



Example:
        

 
namespace TheExplicitConversion
{
    class Program
    {
        static void Main(string[] args)
        {
            long l = 13656L;
            int i = (int)l; //explicit conversion

            int m = 10;
            float f = 0;
            f = m;
            f = 0.5F; //implicit conversion                                
         }
      }
  }

        
namespace NumericText
{
    class Program
    {
        static void Main(string[] args)
        {
          
            //Conversion of numeric type in text
            int i = 5;
            string SS = i.ToString();
            Console.WriteLine("" + SS);
           
        }
    }
}     


  namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {

            //Conversion of type text in numeric type
            string mValueI = " 15 ";
            string mValueII = " 20 ";

            int a = int.Parse(mValueI);
            int b = int.Parse(mValueII);
            int c = a + b;
            //Console.WriteLine("Result:" ,c);
            Console.WriteLine("Result:", c);
              
        }
    }
}

No comments:

Post a Comment