ABPerson
ABPerson

Reputation: 521

int.Parse Fails On Valid String

I am completely lost with this.

So, I'm trying to use int.TryParse to parse a string, a perfectly valid string containing literally the number "3", that's it. But, it's giving me back false when I try to parse it.

This is how I'm using it - I've debugged it, and int.TryParse is definitely giving back false, as the code in the if statement runs:

if (!int.TryParse(numberSplitParts[0], out int hour))
        return false;

And I've looked in the debugger numberSplitParts[0] is definitely the digit 3, that's perfectly valid! Valid String In Debugger

Now, I did some research and people have been saying to use the invariant CultureInfo, so, I did that, here's the new updated line (I also tried NumberStyles.Any and that didn't work either):

 if (!int.TryParse(numberSplitParts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int hour))
        return false;

That also doesn't work - it continues to give me back false, and hour is 0.

I've tried all of the other number types as well - byte.Parse, Int16.Parse etc. All of those gave back false too.

And, I've tried regular int.Parse, and that simply gives me the following exception:

System.FormatException: 'Input string was not in a correct format.'

But then, I tried it in a different project, so, I replicated the string array and everything, and it worked there - both with and without "InvariantCulture".

So, I'm suspecting that the project I'm working in must be configured in such a way that caused int.Parse/int.TryParse to not work. This is in a class library, that is being accessed from a UWP Application - could the fact that this is running under UWP have any effect?

Upvotes: 1

Views: 1619

Answers (1)

canton7
canton7

Reputation: 42225

As discussed in the comments, this is due to a couple of LEFT-TO-RIGHT MARK Unicode characters in your input.

When you did your test in a different project, you probably hard-coded the string "3", or got your input from a source which didn't add the same invisible characters.

A better test is to check whether numberSplitParts[0] == "3", either in the watch window or in your code itself. Another is to set numberSplitParts[0] = "3" in your UWP project, and see if that parses correctly.

In my experience, most cases of "this string looks fine but <stuff> fails" is due to invisible Unicode characters sneaking into your input.

Upvotes: 1

Related Questions