Casting and Converting types in .Net (using C#) - Part I
C# is a type-safe and strongly typed language. If your method expects int and you are passing string, will not be compiled. Here the casting/converting plays a role. .Net allows you to convert between types.
This article is first of a two-part series. The second focuses on casting and the current is on converting. The following are the links for both parts.
Part I : Converting
Part II : Casting
Converting:
For primitive types we convert and for complex types we use type casting. There are two types of converting i.e. implicit and explicit. Implicit conversion is taken care by CLR.1 Explicit conversion, developer needs to handle.
Implicit:
Implicit conversions are handled by CLR. For this developer need not give any special syntax to convert.
int amount = 99;
float price = amount;
Explicit:
Explicit conversion needs developer effort. It requires syntax. Explicit conversion is done at runtime. If unable to convert, then an exception will be thrown. .Net framework provides you a dedicated static class ‘Convert’ with lots of methods (.ToX()). So what’s the big deal? Use them. Don’t be in a hurry! There are few things we need to consider before using them.
What are the problems?
Developers follow different approaches for getting the desired result. In my team, I’ve seen most usage of the ToString. Wherever there is a need of string, we used to put .ToString() and for other data types, Convert.Whatever. Is it OK? Well, .Net doesn’t have control on the input object what you have provided. I mean, it will throw compile errors if the expected type is not provided, but during runtime only it can say whether the provided input can be converted or not. Let’s assume a simple scenario. Let’s say I am having data displayed in grid and on selection of any row, I am redirecting to other page by passing record ID in QueryString.2 Since, I know the record ID is integer, am using Convert.ToInt32 method to convert a QueryString to int . This will work perfectly in normal conditions. But as said “Never trust external data”, what happens, if the user changes url manually, like id=abc? Exception... And I feel application should not throw Exceptions for these small things. We can handle it in better way and can pass a message to user that invalid id is provided. Another example, we are driven by objects. And for converting object to string, we use .Tostring(). For eg. Session[“name”]=”Fionna”; 3 Now I want the name. I do string name=Session [“name”].Tostring(). What if the Session[“name”] is null. Invoking a method on null. NullReferenceException!
How to deal with them?
There are hundreds of methods for converting in Convert class. I am not going to deal with all them. We will see string, int and DateTime.
String Conversions:
The most common operation performed by any developer is converting a type to String. This can be offered to any type, since all types are inherited from object and any object can be converted to string. As we have seen in previous statements, the dangers of .ToString(). If the object is null where we apply .ToString(), the most loved NullReferenceException – “object reference not set to an instance of an object” is thrown. Generally, there are two ways to convert to string. One is ToString from convert class and the other is ToString method in each type. If you search for what is the difference between Convert.ToString() and .ToString(), you will get tons of sites explaining the difference. And that will be the way of handling nulls. A Convert.ToString will not throw any exception if the passed object is null, whereas .ToString() throws a NullReference exception.
string nullString = null;
string resultString;
//No Exception. But, resultString is null only.
resultString = Convert.ToString(nullString);
//throws NullReferenceException
resultString = nullString.ToString();
Obviously, we should use Convert.ToString where there are chances of null. But, the result is null only. Again, we are under gun. Why don't we return empty if the result is null?
string nullString = null;
string resultString;
resultString = Convert.ToString(nullString)
//Null coalescing operator.
resultString = resultString ?? string.Empty; 4
I used null check widely instead of returning empty. Again this is your choice. Coz, the best way to work on this is string.IsNullOrEmpty which checks for both null and empty.
string nullString = null;
string resultString;
resultString = Convert.ToString(nullString);
if (!string.IsNullOrEmpty(resultString))
{
//Do your logic here.
}
Do you like ToString more than Convert.ToString as I do?? .ToString is easy to code than Convert.ToString. Typing Convert.ToString and using every where is pretty difficult for me. Then I followed ExtensionMethods5 (frame work should be 3.0 or higher). I wrote an extension method for the same.
public static class ExtensionMethods
{
public static string ToStringOrEmpty(this object value)
{
return value == null ? string.Empty : value.ToString();
}
}
If you use extension methods, then the code snippet would be…
string nullString = null;
string resultString;
resultString = nullString.ToStringOrEmpty();
Int Conversions:
We can convert an object to int by using Convert.ToInt32 and int.Parse. The difference would be the same as we’ve seen in string conversions. If null is passed to Convert.ToInt32, it returns default of int i.e., 0(zero). Whereas int. Parse throws ArgumentNull exception.
string nullString = null;
int resultInt;
//returns 0
resultInt = Convert.ToInt32(nullString);
//throws ArgumentNullException
resultInt = int.Parse(nullString);
Thank God! We handled null a better way. Is it enough?? What if the value is some text which cannot be converted to int?? Is Convert.ToInt32 is handling this?? No. If you are passing an invalid text for converting into int, then we get format exception, “Input string was not in a correct format.”
string invalidInt = "abc";
int resultInt;
//throws FormatException
resultInt = Convert.ToInt32(invalidInt);
//throws FormatException
resultInt = int.Parse(invalidInt);
Here it comes, the wonderful feature “TryParse”. TryParse is similar to parse, except it does not throw exception if the conversion fails and our output int value is default.
string invalidInt = "abc";
int resultInt;
//No exception. Best one.
bool isInt = int.TryParse(invalidInt, out resultInt);
Check if the return bool is true. If false, the input is invalid. If you use .net 3.0 or higher, then define your own extension method, ToInt
public static class ExtensionMethods
{
public static bool IsInt(this string value)
{
int num;
return int.TryParse(value, out num);
}
public static int ToInt(this string value)
{
int num;
int.TryParse(value, out num);
return num;
}
}
Here, we have two extension methods offered for a string. One is to check whether the input can be converted to int. And the other is returning int, if valid, else returning 0(zero). The best part is, it handles null too.
DateTime Conversions:
This is similar to int discussion. So, am not going to elaborate. For null, Convert.ToDateTime returns default of DateTime, i.e.,1/1/0001 12:00:00 AM and DateTime.Parse throw exception. And for invalid data to be converted into DateTime…
string nullString = null;
DateTime resultDateTime;
//returns 1/1/0001 12:00:00 AM
resultDateTime = Convert.ToDateTime(nullString);
//throws ArgumentNullException
resultDateTime = DateTime.Parse(nullString);
And invalid data to be converted to DateTime...
string invalidDateTime = "abc";
DateTime resultDateTime;
//throws FormatException
resultDateTime = Convert.ToDateTime(invalidDateTime);
//throws FormatException
resultDateTime = DateTime.Parse(invalidDateTime);
Same as Int. We have to use TryParse instead of parse.
string invalidDateTime = "abc";
DateTime resultDateTime;
//Converts if data is valid. For invaild data, result is default DateTime
DateTime.TryParse(invalidDateTime, out resultDateTime);
And extension methods will be
public static class ExtensionMethods
{
public static bool IsDateTime(this string value)
{
DateTime dt;
return DateTime.TryParse(value, out dt);
}
public static DateTime ToDateTime(this string value)
{
DateTime dt;
DateTime.TryParse(value, out dt);
return dt;
}
}
Using them...
string invalidDateTime = "abc";
DateTime resultDateTime = invalidDateTime.ToDateTime();

- Common Language Runtime (CLR) is managed execution environment which takes care of JIT, garbage collection, exception handling...
- Query string is the part of a URL, used to pass small data across pages.
- Session is a state management technique in asp.net which provides facility to store and retrieve the data for every user.
- The null-coalescing operator(??) is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
- Extension methods enables to add" methods to existing types. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.