11 Replies - 780 Views - Last Post: 09 July 2013 - 09:30 AM Rate Topic: -----

#1 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Understanding int.TryParse

Posted 16 June 2013 - 09:13 AM

TryParse is pretty important and up until now I really haven't found a definitive use for it other than making sure my small "challenge" programs can properly interpret entered values.

And, up until now I haven't used it because the book I am reading really hasn't explained it and really didn't expect me to use it. While I think the book I am reading (along with tutorials and feedback from this forum) really has given me a strong foundation, it has also been reinforcing some bad practices.

What I mean by that is the book is expecting me to use only things I have learned in the book to complete challenges at the end of each chapter. That's not to say that the techniques I've used are bad in any way, but there are definitely some much better ways to handle the programs I've been writing to satisfy these challenges. I know that in the coming months I'll be able to write versions of the same programs using code that's not only logical, but also simplifies the program. For example, it may be a better idea to use an array instead of a bunch of if else statements depending on the situation.

TryParse is still one of those things that has me a bit confused. I'm not confused about it's function. I'm a bit confused on the logic and how to implement it into a program easily.

For example, here is a bit of code another user showed me that uses TryParse instead of just Parse.

	        {
	            string userInput = Console.ReadLine();
	            bool isThisANumber;
	            int parsedNumber;
	            isThisANumber = int.TryParse(userInput, out parsedNumber);
	        }


DotNetPerls does have an example of this, but it uses a couple of if statements and it's a bit different than the code I listed. It also has the bool listed on the same line as isThisANumber, which I am sure is perfectly legal. Still, I think the above example is perfect for the discussion.

I tried to break this down line by line and I can see what's going on, but there are just a couple of things that confuse me.

I am assuming that once the program starts, it expects an input from the user, whether that be a string representation of a number or an actual string (letters). Once the user enters the data and presses enter, I assume userInput = (what the user entered). The next line is a simple boolean declaration and then an integer declaration. So now we have two variables, one that will be assigned to be either true or false, and the other will be assigned an integer.

I am also assuming that the next line is just taking the data the user entered and checking to see if it's an integer or a string. If it's an integer, that integer will be assigned to the variable parsedNumber because isThisANumber is considered true. If it's not an integer, the isThisANumber will now be false and the program will return 0.

Do I have that correct? If I left anything out, please feel free to correct me.

What I am a bit confused about is the boolean statement. Do we always need to include the boolean when using TryParse? Does it work any other way?

I can sort of see what's happening. isThisANumber can only have two values, true or false. If it's true, then the integer gets passed back (or however you say it) out and assigned to the variable parsedNumber.

The reason I bring this up is because it would seem logical that from now on I include this as sort of a template for checking user input when expecting an integer from the user. Am I wrong about that?

I'd like to discuss this because it's something I feel is critical to my progression.

This post has been edited by Semus: 16 June 2013 - 09:13 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Understanding int.TryParse

#2 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3362
  • View blog
  • Posts: 11,398
  • Joined: 12-December 12

Re: Understanding int.TryParse

Posted 16 June 2013 - 09:21 AM

Your understanding is correct.

The boolean variable will store a value of either true or false confirming whether or not C# was able to convert what the user entered into an integer.

if (isThisANumber) {
    // whey'hay! we can double it..
    parsedNumber *= 2;
} else {
    // Doh! not a number (integer),
    // we'll have to ignore parsedNumber and do something else.
}

(just like you doubled your thread ;) )
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3362
  • View blog
  • Posts: 11,398
  • Joined: 12-December 12

Re: Understanding int.TryParse

Posted 16 June 2013 - 09:33 AM

If you are not already, you should always supplement your studies by reading the official MSDN documentation. Even if they don't make much sense initially, or their examples are a little more complicated. The more comfortable you are at MSDN, and able to navigate the site, the better.
Was This Post Helpful? 1
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Understanding int.TryParse

Posted 16 June 2013 - 09:44 AM

Don't over think it. Don't try to add complexity where it doesn't exist. The short explanation:

int.Parse will throw an exception if you try to parse "YogiBear"
int.TryParse will NOT throw an exception and will return a value of zero

So from there it is up to you how to best incorporate those into your architecture.

If valid values can only be 1 and greater, then .TryParse works for you. It won't throw an exception and you can test if the return is less than 0.

If 0 is a valid value however, you won't know if the user input was zero or if .TryParse absorbed the error and gave you a false 0 as a return. You might be better off using .Parse and trapping the exception to confirm the validity of the user input.

int BobsAge = -1; // Both invalid and common flag in .NET
while (BobsAge < 1)
{
   try
   {
   
       int.Parse(GetUserInputMethod(), out BobsAge);
       return BobsAge; // if it got this far then no exception
   }
   catch
   {
      // User input could not be parsed.
      // Continue loop until no exception
      Continue;
   }
}


UPDATE: My mistake was corrected by Momerath

View PostMomerath, on 16 June 2013 - 08:16 PM, said:

View PosttlhIn`toq, on 16 June 2013 - 09:44 AM, said:

If 0 is a valid value however, you won't know if the user input was zero or if .TryParse absorbed the error and gave you a false 0 as a return. You might be better off using .Parse and trapping the exception to confirm the validity of the user input.


You will know if TryParse failed a parse vs parsing a zero, the return value will tell you. If it returns 'true' then it parsed a value, 'false' and the parsing failed.

Parse returns a value on a successful parse and throws an exception if it doesn't.
TryParse returns a boolean indicating if the value was successfully parsed and places the value into the out variable you supplied. If the parse failed, it will set the out variable to its default value.

This post has been edited by tlhIn`toq: 17 June 2013 - 06:27 AM

Was This Post Helpful? 0
  • +
  • -

#5 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Understanding int.TryParse

Posted 16 June 2013 - 09:48 AM

View PosttlhIn`toq, on 16 June 2013 - 09:44 AM, said:

In the future please don't open duplicate threads for the same thing.


That was not my intention. When I hit the "post topic" button, it sat there for over a minute, so I hit the button again. Something I won't repeat. I apologize that the thread was duplicated. Again, that was not my intention. Just an accident.

View PosttlhIn`toq, on 16 June 2013 - 09:44 AM, said:

Don't over think it. Don't try to add complexity where it doesn't exist. The short explanation:

int.Parse will throw an exception if you try to parse "YogiBear"
int.TryParse will NOT throw an exception and will return a value of zero

So from there it is up to you how to best incorporate those into your architecture.

If valid values can only be 1 and greater, then .TryParse works for you. It won't throw an exception and you can test if the return is less than 0.

If 0 is a valid value however, you won't know if the user input was zero or if .TryParse absorbed the error and gave you a false 0 as a return. You might be better off using .Parse and trapping the exception to confirm the validity of the user input.



I like your Try, Catch method of checking to see if 0 is valid. That's something I'll keep in mind.

This post has been edited by Semus: 16 June 2013 - 09:52 AM

Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Understanding int.TryParse

Posted 16 June 2013 - 10:00 AM

No worries mate. I promise nobody is mad or going to stamp "no desert" on your meal card. The site has had some issues with slow downs lately and the admins are looking into it. This is just a manifestation of that same issue.
Was This Post Helpful? 0
  • +
  • -

#7 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Understanding int.TryParse

Posted 16 June 2013 - 10:05 AM

So if I wanted to print out an error message if it couldn't parse the input, I could write it like this...

pay no attention to the commented out lines(that was just a test)

            //Console.Write("Please enter a number: ");
            string userInput = Console.ReadLine();
            int parsedNumber;
            bool isThisANumber = int.TryParse(userInput, out parsedNumber);

            if (isThisANumber == false)
            {
                Console.WriteLine("That is not a number!");
            }
            else
            {
            Console.WriteLine(parsedNumber);
            }

            Console.ReadLine();

This post has been edited by Semus: 16 June 2013 - 10:06 AM

Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5480
  • View blog
  • Posts: 11,762
  • Joined: 02-June 10

Re: Understanding int.TryParse

Posted 16 June 2013 - 10:16 AM

View PostSemus, on 16 June 2013 - 11:05 AM, said:

So if I wanted to print out an error message if it couldn't parse the input, I could write it like this...


Are you asking us a question? Or telling us what you have tried and it works?
Was This Post Helpful? 0
  • +
  • -

#9 Semus  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 126
  • Joined: 27-May 13

Re: Understanding int.TryParse

Posted 16 June 2013 - 10:55 AM

View PosttlhIn`toq, on 16 June 2013 - 10:16 AM, said:

View PostSemus, on 16 June 2013 - 11:05 AM, said:

So if I wanted to print out an error message if it couldn't parse the input, I could write it like this...


Are you asking us a question? Or telling us what you have tried and it works?

Sorry about that. I was just stating that this is what I tried and yes, it does work. I should have been more specific. If there is any error in my logic feel free to point it out, but it was really just a statement rather than a question.
Was This Post Helpful? 0
  • +
  • -

#10 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Understanding int.TryParse

Posted 16 June 2013 - 07:16 PM

View PosttlhIn`toq, on 16 June 2013 - 09:44 AM, said:

If 0 is a valid value however, you won't know if the user input was zero or if .TryParse absorbed the error and gave you a false 0 as a return. You might be better off using .Parse and trapping the exception to confirm the validity of the user input.


You will know if TryParse failed a parse vs parsing a zero, the return value will tell you. If it returns 'true' then it parsed a value, 'false' and the parsing failed.

Parse returns a value on a successful parse and throws an exception if it doesn't.
TryParse returns a boolean indicating if the value was successfully parsed and places the value into the out variable you supplied. If the parse failed, it will set the out variable to its default value.
Was This Post Helpful? 2
  • +
  • -

#11 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3552
  • View blog
  • Posts: 11,009
  • Joined: 05-May 12

Re: Understanding int.TryParse

Posted 16 June 2013 - 08:00 PM

Although it is actually implemented the other way around, one way to think of TryParse() is like this:

int MyTryParse(string s, out int value)
{
    try
    {
        value = 0;
        value = int.Parse(s);
    }

    catch()
    {
        return false;
    }
    return true;
}


Was This Post Helpful? 1
  • +
  • -

#12 Michael26  Icon User is offline

  • DIC-head, major DIC-head
  • member icon

Reputation: 355
  • View blog
  • Posts: 1,521
  • Joined: 08-April 09

Re: Understanding int.TryParse

Posted 09 July 2013 - 09:30 AM

View PostSemus, on 16 June 2013 - 07:05 PM, said:

So if I wanted to print out an error message if it couldn't parse the input, I could write it like this...

pay no attention to the commented out lines(that was just a test)

            //Console.Write("Please enter a number: ");
            string userInput = Console.ReadLine();
            int parsedNumber;
            bool isThisANumber = int.TryParse(userInput, out parsedNumber);

            if (isThisANumber == false)
            {
                Console.WriteLine("That is not a number!");
            }
            else
            {
            Console.WriteLine(parsedNumber);
            }

            Console.ReadLine();



This is just my personal preference but i write if/else like this
if(//expresion is true)
{
  //execute if true 
}
else
{
  //execute if false
}

You just reversed the if/else roles.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1