Skip to content

3 ways to check for conversion errors in C#

April 7, 2009

Casts should be avoided because they can cause errors that cannot be detected until runtime.

Although C# offers Generics in an attempt to limit the amount of casting one uses in his code, sometimes you just can’t evade them.  One such example is when you create threads that should receive parameters on startup (this is done by using the ParametrizedThreadStart delegate). Of course, you could use a synchronized structuer after creating a simple thread with the ThreadStart delegate, but it would not be the same, would it?

So, here are three solutions to the casting problem. Always use one of them, it’s good programming practice.

1.  Catching InvalidCastException

string s = "hi";
Object o = s;
Graphics i = null;
      i = (Graphics)o;
catch (InvalidCastException ex)
      Console.WriteLine("bad cast1");

2. Using the is operator

if (!(i is Graphics)) Console.WriteLine("bad cast2");

3. Using the as operator

if ((i as Graphics) == null) Console.WriteLine("bad cast2");
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: