Page 1 of 1

What does this c# code do?

Posted: Fri Apr 10, 2009 6:23 pm
by Keevu

Code: Select all

public bool IsNumeric(string s)
        {
            try
            {
                Double.Parse(s);
            }
            catch
            {
                return (false);
            }

            return (true);
        }
why is it useful? my programs work without it. But my class project tutorials always tell me to put it in.

Re: What does this c# code do?

Posted: Fri Apr 10, 2009 7:21 pm
by wearymemory
First of all, ask your professor before coming here. He will probably give you the best answer, given the fact that he knows your circumstances more than we do.

Also, If you're incapable of deciphering that, but you know what try catch statements are, then there's a problem. Otherwise, your teacher shouldn't be telling you to apply code to your program when you don't even know what it does. That's just my honest opinion, not that you asked.

IsNumeric returns a bool dependent on whether the given string (s) is a number. It does the latter by first trying to parse the given string as a double, if it fails, or the input is not actually a number, it throws an exception which is caught by your catch statement which then returns false, otherwise, it returns true.

Looking up the words "is" and "numeric" in Webster's would have hopefully answered some of your question.

Pseudo code:

Code: Select all

if(IsNumeric(TextBox.Text)
{
  // Apply code.
}
else
{
  // Scream at user.
}
Edit: I'm quite concerned with the post you made here: http://elysianshadows.com/phpBB3/viewto ... art=999999

Re: What does this c# code do?

Posted: Sun Apr 19, 2009 4:34 pm
by LeonBlade
Your teacher probably wants you to put it in there in case you go back and edit your code maybe?

Code: Select all

public bool IsNumeric(string s)
{
     try
     {
          Double.Parse(s);
     }
     catch
     {
          return (false);
     }
     return (true);
}
First off this is a method which returns a boolean value (true/false) and judging by the name IsNumeric it tests a string if it is a number or not.
The method requires a string value which is labeled s.

The try catch allows you to try something without breaking your program. It will try whats in the block and catch an error which is in the catch section and return false in this case.

Here you are trying to parse your string as a double. If you are successful, then you will return true, meaning that your string was a number.
If you aren't successful in parsing your string, then that means it wasn't a number and returns false.

So, that's what that method does.
But like wearymemory said, you should ask your teacher about this stuff, but it's alright to come here and ask.

EDIT: I just noticed now that wearymemory already gave an explanation lol... I didn't notice it at first, I thought you were just telling him not to ask here...