The “System.Convert” class provides several methods to perform explicit casting.
System.Convert.ToSByte(value);
Converts the value into “sbyte” type.
System.Convert.ToByte(value);
Converts the value into “byte” type.
System.Convert.ToInt16(value);
Converts the value into “short” type.
System.Convert.ToUInt16(value);
Converts the value into “ushort” type.
System.Convert.ToInt32(value);
Converts the value into “int” type.
System.Convert.ToUInt32(value);
Converts the value into “uint” type.
System.Convert.ToInt64(value);
Converts the value into “long” type.
System.Convert.ToUInt64(value);
Converts the value into “ulong” type.
System.Convert.ToSingle(value);
Converts the value into “float” type.
System.Convert.ToDouble(value);
Converts the value into “double” type.
System.Convert.ToChar(value);
Converts the value into “char” type.
System.Convert.ToString(value);
Converts the value into “string” type.
System.Convert.ToBoolean(value);
Converts the value into “bool” type.
Demo on Casting with Conversion Methods
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConversionMethods
{
class Program
{
static void Main(string[] args)
{
int x = 10;
long y = x; //implicit
byte z = Convert.ToByte(x); //explicit
double p = x; //implicit
int q = Convert.ToInt32(p); //explicit
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.WriteLine(p);
Console.WriteLine(q);
char c = 'A';
string s = Convert.ToString(c); //explicit
Console.WriteLine(s);
Console.Read();
}
}
}
IMP Note:
By default, C# recognizes all the integer constants as the type of “int”.
In the same way, C# recognizes all the floating point constants as the type of “double”.