In this article I am going to dicuss about C# Type Casting in detail but before that if you have read my previous article of C# Data Types then must read it know about the different types of datatypes. In C#, Type Casting or Type Conversion is the process to change one data type value into another data type. In C#, Type Casting is only possible if datatypes are compatible with each other otherwise we will see the compilation error cannot Implicitly convert one data type to another. In C# we have to declare the variable first with its data type before using the particular variable therefore we cannot redeclare the same variable but sometimes while doing complex programming we have to change its data type so that’s why type casting comes into an existence.
Types of C# Type Casting
In C# Type Casting or Type Conversion is done automatically by the compiler or done manually with the developer. It totally depends on type of datatypes. Because Type Casting is done by compiler and developer both therefore it is classified into two types:
- Implicit Type Casting
- Explicit Type Casting
Implicit Type Casting
In C# Implicit Type Casting or Type Conversion is done automatically by the compiler without loosing any data but implicit type casting is done only from small datatype to big datatype. If we trying to do typecasting from big datatype to small datatype then we have to use explicit type casting otherwise we got compilation error. This type of type casting is safe and easy to use. In C# compiler can perform implicit type casting on the following data types.
Convert from Data Type | Convert to Data Type |
byte | short, int, long, float, double, |
short | int, long, float, double |
int | long, float, double |
long | float, double |
float | double |
In above table you can clearly see that compiler can convert which datatype to which datatype. If your code contains this type of datatypes and want to convert it to one of the datatypes then compiler can automatically do the type casting. For more clear understanding let see one small program that demonstrates the working of Implicit type casting in csharp(C#).
using System; namespace ImplicitTypeCasting { class Program { static void Main(string[] args) { int number = 500; double numDouble = number; // Implicit Conversion // Value Before Conversion Console.WriteLine("number value: "+ number); Console.WriteLine("Int Size in Bytes: "+sizeof(int)); // Value After Conversion Console.WriteLine("numDouble value: "+numDouble); Console.WriteLine("Double Size in Bytes: "+sizeof(double)); Console.ReadKey(); } } } Output: number value: 500 Int Size in Bytes: 4 numDouble value: 500 Double Size in Bytes: 8
Explicit Type Casting
If you want to convert the large data type to a small data type in C#, then you need to do the same explicitly using the cast operator. But in case of explicit type casting there will be chances of losing data or may be type conversion not possible due to some reasons. Let see the explicit type casting with an example:
using System; namespace ExplicitTypeCasting { class Program { static void Main(string[] args) { double numDouble = 9.23; // Explicit Type Casting int numInt = (int)numDouble; // Value Before Conversion Console.WriteLine("Original double Value: " + numDouble); // Value After Conversion Console.WriteLine("Converted int Value: " + numInt); Console.ReadKey(); } } } Output: Original double Value: 9.23 Converted int Value: 9
In above code you can see with explicit type casting we have loss the data as the actual value is 9.23 and when we have convert this double value to int we got 9 because integer can only contains non decimal numbers. So point to remember is that with explicit type casting there will be high chance of loosing data.
Type Conversion with C# Helper Methods
In C# type casting can also possible with csharp helper methods which is used to convert one datatype value into another datatype. The C# helper methods comes into existence for type casting where datatypes are not compatible with each other. For example we have one string one we want to convert that string to int using explicit typecasting but this time we got error because string datatype is not compatible with int. For example:
using System; namespace TypeCastingDemo { class Program { static void Main(string[] args) { string str= "100"; int i1 = (int)str; Console.ReadKey(); } } } //when we run this program we got error cannot convert from string to int because when we do explicit type casting first it will check datatype compatiblity and then checks then checks the datatype.
So doing this type of conversion we have to use C# helper methods. There are lots of C# helper methods which is used for type conversion which is discussed below:
Method | Description |
ToBoolean | It will converts a type to boolean value |
ToChar | It will converts a type to character value |
ToByte | It will conversts a value to byte value |
ToDecimal | It will converts a value to decimal point value |
ToDouble | It will converts a datatype to double data type |
ToInt16 | It will converts a type to 16-bit integer |
ToInt32 | It will converts a type to 32-bit integer |
ToInt64 | It will converts a type to 64-bit integer |
ToString | It will converts a given type to string |
ToUInt16 | It will converts a type to unsigned 16 bit integer |
ToUInt32 | It will converts a type to unsigned 32 bit integer |
ToUInt64 | It will converts a type to unsigned 64 bit integer |
Let see one example for more clear understanding:
using System; namespace TypeCastingWithHelperMethods { class Program { static void Main(string[] args) { string str = "100"; int i1 = Convert.ToInt32(str); //Converting string to Integer double d = 123.45; int i2 = Convert.ToInt32(d); //Converting double to Integer float f = 45.678F; string str2 = Convert.ToString(f); //Converting float to string Console.WriteLine("Original value str: "+ str + " and Converted Value i1: "+i1); Console.WriteLine("Original value d: "+ d + " and Converted Value i2: "+i2); Console.WriteLine("Original value f: "+ f +" and Converted Value str2: "+str2); Console.ReadKey(); } } } Output: Original value str: 100 and Converted Value i1: 100 Original value d: 123.45 and Converted Value i2: 123 Original value f: 45.678 and Converted Value str2: 45.678
When we are using the C# helper method to convert a value to a particular type, if types are not compatible, then it will not throw you any error at compile time. At run time, it will try to convert the value to that particular type and if the value is compatible then it will convert and if the value is not compatible, then it will throw a runtime error. For example if you have declare an string=”WebTutorialStack” and you trying to convert this to int then at compile time it will not throw error but at runtime convert class helper method will not able to understand this therefore it throws runtime error. In order to avoid runtime error we can use tryparse method in csharp(C#).
TryParse Method in C#
When we use the Parse method, if the conversion is not possible then at runtime, we will get an exception which is not a good thing. Because if conversion is not possible then we should show some information to the user and we should proceed further. To do so, the built-in value type class in C# is provided with the TryParse method. To understand this TryParse Method in C# let see one program.
using System; namespace TryParseMethodDemo { class Program { static void Main(string[] args) { string str1 = "100"; bool IsConverted1 = int.TryParse(str1, out int I1); if (IsConverted1) { Console.WriteLine("Original String value: " + str1 + " and Converted int value: "+I1); } else { Console.WriteLine("Try Parse Failed to Convert " + str1 +" to integer"); } string str2 = "Hello"; bool IsConverted2 = int.TryParse(str2, out int I2); if (IsConverted2) { Console.WriteLine("Original String value: " + str2 + " and Converted int value: "+I2); } else { Console.WriteLine("Try Parse Failed to Convert " + str2 + " to integer"); } Console.ReadKey(); } } } Output: Original String value: 100 and Converted int value: 100 Try Parse Failed to Convert Hello to integer
Conclusion
In this article of C# tutorials we have discussed in detail that what is typecasting, types of typecasting and different ways for typecasting in c# using helper methods and TryParse method. Instead of this two there is one more way to typecast that is with Parse method.
string str1 = "100"; //Converting string to int type int i = int.Parse(str1);
But the most suitable way is to use TryParse method to avoid runtime error in your program. In my next article I am going to dicuss about different types of operator in csharp with proper examples.