Thursday, November 4, 2010

Alternatives to Try Catch type casting

Back in the early stages of .NET in C# there were limited tools to determine if a cast would work or not.

So typically you'd see something like

int myInt = 0;

try
{
   myInt = (int)TextBox1.Text //some input
}
catch
{
   MessageBox.Show("This is not a valid integer.");
  return;
}

In 2.0 the TryParse came along.  TryParse will return a bool (if the cast worked or not) and put the value of the successful cast into a value.

Example:

int myInt = 0;

if !(int.TryParse(TextBox1.Text, out myInt))
{
  MessageBox.Show("This is not a valid integer.");
}

Visually, this is a little less code but is also a more legitimate way of testing your casting.  Really, you could do a lot more checks using Regular Expressions, etc but something like this is a simple way to do validation in simple scenarios... IE... you just need there to be a number in there not a number with a decimal and x number of digits before and after, etc.

That example was for simple data types... but we can use IS for more complex data types like objects.

The IS keyword basically evaluates if the object to the left of the IS inherits (or is actually) of the same type.  This is useful in places where you want to pass an object as something simpler than it really is to made your function more versatile.

Using the Try Catch paradigm we could do something like this...

public static boolean SaveData(object myObj)
{
     SomeBaseClass b = null;

      try
     {
          b = (SomeBaseClass)myObj;
          return b.SaveData(); //assumes that method returns bool
      }
     catch
     {
         return false;
      }
}

A simpler way is to use the IS keyword...


public static boolean SaveData(object myObj)
{
    SomeBaseClass b;

    if (myObj is SomeBaseClass)
  {
          b = (SomeBaseClasse)myObj;
         return b.SaveData();
   }
  else
  {
   return false;
  }
}

Now in a case like this I'd probably make my SaveData function accept a SomeBaseClass object instead of a regular object and call the save... or make the object implement some type of interface that any object wanting to use this method could call.

However, this is just to give an example of how you can evaluate objects.  Maybe you support some types of objects (or handle them slightly differently) and want to run them all through the same method and this way you can easily do that.

No comments:

Post a Comment