Try and Ye Shall Succeed

have a recurring dream. It happens often enough that I think of it in waking moments. The dream goes like this. (Don’t you hate it when people tell you their dreams? I’ll keep this short.) In the dream, I’m living in a house and everything’s fine. Then one day, I discover a door in the wall, and find a whole wing of the house that I hadn’t previously known existed. Sometimes, good things happen among the unfinished rafters, other times, bad. Either way, in every house I’ve ever owned, I’ve harbored this fantasy that some day I’ll find this “hidden wing”.

Amazingly, this time it actually happened. The guy who built the house we landed in was a bit, well, eccentric. It’s a beautiful place, with lots of interesting details, and we knew from the outset that there was space above the garage that wasn’t connected to the house, and wasn’t built out. Bored one day, we climbed up a ladder into the unfinished space, and it was as if I was experiencing my dream, in real life. No walls, plywood floor, ceiling joists, and 700 sq ft of extra space. Now to find a use for it all!

Flip forward a few days (we move fast) and we have contractor drawing plans for a home theater. I’ve always wanted one. I hate having the living room cluttered with wires and big TV and speakers and stuff. A separate space, with a screen that rolls up at night, and a front projector-that’s my kind of place.

?
Figure 1: Projector Manual Image: I attempted to decipher this figure to determine the appropriate projector and screen placement.

Little did I know what I was in for (we won’t even go into the construction issues). Perhaps you’ve tried to deal with screens and projects and stuff, but it’s almost got me wishing for the time when all we had was a 12-inch black and white remote-free TV. The variables involved in determining the correct screen size, placement, material, and geometry have me running for the hills. Some projectors can be hung from the ceiling above the screen, others cannot. The room has to be dark for some projectors; others can handle ambient light. (Our problem is that we’re simply building a room with a projector in it. Apparently, to create an appropriate home theater, you need to create a black room with black walls and ceiling and carpet. No thanks.) I even attempted to decipher the following figure from one of the projector manuals, attempting to determine the appropriate projector and screen placement (see Figure 1). Good luck:

The result? I’ll get professional help. As with most tasks such as this, I suggest finding someone who knows what the heck they’re doing. If you’re in the area in March or April, however, come on by for the inauguration of the theater. I haven’t quite figured what the premiere showing will be. People tend to use big sci-fi epics to show off their systems. Perhaps some Star Wars thing? Send in your suggestions, please! Oh, and what did we learn from all this? When you’re adding a room upstairs, build the stairs first. Climbing a ladder through a hole in the ceiling to haul up framing materials is just no fun.

Converting Data in .NET
As for seeking professional help, it has always seemed to me that converting data from text to numeric values, in the .NET Framework, was always just too much trouble. Sure, the Convert class adds a bunch of methods that handle all the conversions for you, but if your conversion fails, these methods raise an exception.

Let’s start with a simple case: Imagine that you’ve got an application in which the user enters an integer into a text box, and you need to convert it to an integer for storage in a local variable. The following code uses the Int32.Parse method to perform the conversion:

   ' VB   Try      Dim value As Integer = Integer.Parse(TextBox1.Text)      ' Do something with value.   Catch ex As FormatException      MessageBox.Show(        "Please enter an integer.")   End Try      // C#   try   {      int value = int.Parse(textBox1.Text);     // Do something with value.   }   catch (FormatException)   {     MessageBox.Show(       "Please enter an integer.")   }

Although this code isn’t terribly onerous, it does require you to trap an exception, and in the case in which the user enters an invalid value, you pay the price for handling the exception. (If you haven’t noticed, throwing an exception is quite slow, and although it’s not a real problem when the user interface is involved, in data manipulation code, you really see the difference in speed!)

What if you want to allow the user to enter a currency value? That’s handled by the framework, as well, using another overloaded version of the Parse method:

   ' VB   ' Import the System.Globalization namespace:   Try      Dim value As Single = Single.Parse( _         TextBox1.Text, _         NumberStyles.AllowCurrencySymbol Or _         NumberStyles.AllowDecimalPoint)      ' Do something with value.   Catch ex As FormatException      MessageBox.Show( _        "Please enter a currency value.")   End Try      // C#   // Import the System.Globalization namespace:   try   {      float value = float.Parse(textBox1.Text,          NumberStyles.AllowCurrencySymbol |          NumberStyles.AllowDecimalPoint);     // Do something with value.   }   catch (FormatException)   {      MessageBox.Show(        "Please enter a currency value.");   }

That’s not so bad either, right? But it still requires an exception handler. In the .NET Framework 2.0, it’s easier. Instead of handling an exception, you can call the TryParse method instead. (I love the name?so optimistic: “I’m going to TRY REALLY HARD to perform this conversion for you. I might fail, but I’m GOING TO TRY.” I need to sleep more.) The TryParse method, available on all the value types (from Boolean to Uint64), makes it easy to parse text into values. It accepts the value to be parsed, and a by reference/out parameter into which it places the parsed text. The method returns True if it succeeded and False otherwise. No exceptions, no muss, no fuss. (For more information on the new method, check out the help topic titled “Parse vs. TryParse Application Sample” in the MSDN documentation.)

The previous example, coded using the TryParse method, might look like this:

   ' VB   Dim value As Single   If Not Single.TryParse(TextBox1.Text, _      NumberStyles.AllowCurrencySymbol Or _      NumberStyles.AllowDecimalPoint, _      Nothing, value) Then      MessageBox.Show( _         "Please enter a currency value.")   End If      // C#   // Import the System.Globalization namespace:   float value;   if (!float.TryParse(textBox1.Text,       NumberStyles.AllowCurrencySymbol |       NumberStyles.AllowDecimalPoint,       null, out value))   {      MessageBox.Show(        "Please enter a currency value.");   }

Note that the TryParse method doesn’t include an overloaded version that allows you to specify number formatting without also specifying an IFormatProvider instance-the sample code passed Nothing/null for the IFormatProvider parameter. (You can use an IFormatProvider instance to control the formatting of the parsed value. See the MSDN documentation for more information.)

I really like TryParse, and it’s easy to miss. If you find yourself needing to parse data that comes to you from user input, it’s a great tool. It’s even more useful when you need to programmatically manipulate large amounts of data-not having to handle slow exceptions when things go wrong can save you a lot of time.

As with remodeling projects, finding the professional to do the work for you pays off when parsing text. (Yes, a very thin analogy. But I try!) Unless you’re way smarter than me, find someone who knows what they’re doing when it comes time to pick out the projector and screen. I’ll report in on the success of the venture next time, once it’s all up and running.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

technology leadership

Why the World Needs More Technology Leadership

As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job