Welcome to AspAdvice Sign in | Join | Help

C# Type Conversion

I have been running into some issues with type conversion lately.  I never have quite figured out the differences between all the different ways you can do type conversions.  There are 3 that I use throughout my code.

  1. (int) myVariable
  2. myVariable as int
  3. Convert.ToInt32(myVariable)

I found a few articles on MSDN regarding the subject that helped clear the water a little. 

If anyone else has any good references surrounding type conversions, please let me know.

Published Thursday, February 10, 2005 7:26 PM by gstark

Comments

Thursday, February 10, 2005 7:40 PM by gstark

# re: C# Type Conversion

1 is a cast. This means that you are saying make myVariable type int, no matter what. If for some reason the runtime can't do that you will get an exception.

2 is a little tricky. Your example won't compile beause 'as' only applies to refrence types (classes not structs). That said, as is like cast except if the runtime can't make the type conversion; it returns null. It doesn't throw an exception.

3 is a framework layer that supports the IConvertable interface infrastrcuture. It has nothing to do with the runtime or casting in a traditional sense. 3 is generally considered a 'best practice' way to perforom conversoins on common types.

hth,
Paul
Thursday, February 10, 2005 9:25 PM by gstark

# re: C# Type Conversion

And don't forget this ugly one:
4: int x = Int32.Parse(y.ToString());

Sadly, (int)"1" doesn't work, so I often resort to Int32.Parse, myself.

Anonymous comments are disabled