Type Conversion

There are times when we would want to convert one data type to another data type. This conversion is called Type Casting. C# provides 2 types of casting Implicit Type Casting: These conversions are done

There are times when we would want to convert one data type to another data type. This conversion is called Type Casting.

C# provides 2 types of casting

  1. Implicit Type Casting: These conversions are done by C# in a type-safe manner.
  2. Explicit Type Casting: These conversions are done by the users using Pre-defined functions.
SnoMethodDescription
1ToBooleanConverts a type to a Boolean value.
2ToByteConverts a type to a byte.
3ToCharConverts a type to a single character.
4ToDateTimeConverts a type (integer or string type) to date-time.
5ToDecimalConverts a floating point or integer type to a decimal type.
6ToDoubleConverts a type to a double type.
7ToInt16Converts a type to a 16-bit integer.
8ToInt32Converts a type to a 32-bit integer.
9ToInt64Converts a type to a 64-bit integer.
10ToSbyteConverts a type to a signed byte type.
11ToSingleConverts a type to a small floating point number.
12ToStringConverts a type to a string.
13ToTypeConverts a type to a specified type.
14ToUInt16Converts a type to an unsigned int type.
15ToUInt32Converts a type to an unsigned long type.
16ToUInt64Converts a type to an unsigned big integer.

Demo:

using System;
namespace Csharp_ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "500";
            int v1 = Convert.ToInt32(s);
            int.TryParse(s,out int v2);

            string s1 = v1.ToString();

            Console.WriteLine("value stored in v1 = {0} and its data type is {1}",v1, v1.GetType().ToString());
            Console.WriteLine("value stored in v2 = {0} and its data type is {1}", v2, v2.GetType().ToString());
            Console.WriteLine("value stored in s1 = {0} and its data type is {1}", s1, s1.GetType().ToString());

            Console.ReadKey();
        }
    }
}

Leave a Reply

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