Updated : Jan 08, 2022 in Articles

Type casting in Csharp

 Def: The process of converting value from one datatype to another data type is called casting.
This is of Two types.
1.Implicit casting:The value can be converted by the compiler automatically,without using any extra statement.
2.Explicit casting:The value can be converted by the programmer using conversion method.

Implicit casting

Implicit casting is possible in the following cases.
Any numeric value from lower to higher type
  Ex:   byte to short
        Short to int 
        Float to double

Any numerical value from non-decimal type to decimal type
  Ex:   int to float
        Long to double

Explicit casting

Explicit casting should be performed in the following cases.
Any numerical value from higher type to lower type.
any numerical value from decimal type to non-decimal type
Any value from numerical type to non-numerical type.

Syntax:(target data type)variable=(target data type)value

Example:

class Program
    {
        static void Main(string[] args)
        {
            int x = 10;
            long y = x;//implicit
            byte z = (byte)x;//explicit
            double p = x;//implicit
            int q = (int)p;//explicit
            Console.WriteLine(x);
            Console.WriteLine(y);
            Console.WriteLine(z);
            Console.WriteLine(p);
            Console.WriteLine(q);
            Console.ReadLine();
        }
    }

Explicit casting using conversion Methods:

1.Convert.ToSbyte(value);Covert the value into sbyte type.
2. Convert.ToByte (value);convert the value into byte type
3. Convert.ToInt16 (value); convert the value into short type
4. Convert.ToUInt16 (value); convert the value into ushort type
5. Convert.ToInt32 (value); convert the value into int type
6. Convert.ToUInt32 (value); convert the value into uint type
7. Convert.ToInt64 (value); convert the value into long type
8. Convert.ToUInt64 (value); convert the value into ulong type
9. Convert.ToSingle (value); ->convert the value into float type
10. Convert.ToDouble (value); convert the value into Double type
11. Convert.ToString (value); convert the value into string type
12. Convert.ToBoolean (value); convert the value into bool type

Example:
 

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.ReadLine();
        }
    }

When we will go for typecasting

 type casting required when the Right-hand side data type is not equal to Left side data type then we will go for the typecasting concept.

Note: Casting is will be done based on range and not based on size of the data type.

If either byte, short, or char variables are used in an expression they are automatically raised to the rank of int.

using System;
namespace sampleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int n= 566;
            byte b;
            byte c1, c2, c3;
            c1 = c2 = 10;
            c1 = c2 + c3; //Compilation Error
            c1 = (byte)(c2 + c3);
        }
    }
}

Casting long to float

The given example long to float casting is implicit casting because the range of long is smaller than float and float to long explicit casting is required.

class Program
    {
        static void Main(string[] args)
        {
            float f;
            long lng = 20L;
            f = lng;
            lng = (long)f;
        }
    }

Casting int to decimal

The given below example int(10) to decimal casting is implicit casting because the range of int is decimal than float and decimal to float, float to decimal explicit casting is required.

class Program
    {
        static void Main(string[] args)
        {
            float f;
            decimal dec = 10; //Integer to decimal 
            f = (float)dec;
            dec = (decimal)f;
 
        }
    }

Note: decimal type of data type should be explicit casting is required for every other data type if required.      

Casting int to char

The given example char to int casting is implicit casting because of ASCII code format an int to char explicit casting is required.

class Program
    {
        static void Main(string[] args)
        {
            int n;
            char c='0';
            n = c; //Implicit Casting
            c = (char)n; //Explicit Casting
        }
    }

Character:  ‘A’ — ‘Z’             ‘a’ — ‘z’        ‘0’ — ‘9’

ASCII         :  65 — 90           97 —122       48 — 57

Casting string to others

Casting string to other type is invalid its means String cannot be cast see the given below example

class Program
    {
        static void Main(string[] args)
        {
            string str = "s00";
            int n = (int)str; //Invalid- cannot be casted string to int is not allowed
            n = int.Parse(str); //if failes throws, FormatException
            bool bln = int.TryParse(str, out n);
        }
    }

If you want to convert string to another type of data type we need to go for int.parse() or int.Tryparse() methods. Direct casting is not allowed in c#.

Casting int to string

Casting int to string type is invalid its means int directly can not be cast into a string we to required .tostring() method see the given below example

class Program
 
    {
 
        static void Main(string[] args)
 
        {
 
            int n = 0;
 
            string s = n.ToString();
 
            //s = (string) n //direct Casting int to string is invalid
 
        }
 
    }

ToString() in C#:

If you want to convert any other type of data type to string in c# we will use the .tostring() method. ​ ​

Latest posts by DuttaluruVijayakumar (see all)
Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x