2

I am a novice C# learner. I know the basic concepts of this language. While revising the concepts, I stumbled upon one problem - How does Int32.Parse() exactly work?

Now I know what it does and the output and the overloads. What I need is the exact way in which this parsing is accomplished.

I searched on the MSDN site. It gives a very generalized definition of this method (Converts the string representation of a number to its 32-bit signed integer equivalent.) So my question is - How does it convert the string into a 32-bit signed integer?

On reading more, I found out 2 things -

  1. The string parameter is interpreted using the "NumberStyles" enumeration
  2. The string parameter is formatted and parsed using the "NumberFormatInfo" class

I need the theory behind this concept. Also, I did not understand the term - "culture-specific information" from the definition of the NumberFormatInfo class.

Gaurang
  • 1,391
  • 1
  • 13
  • 16
  • 1
    You can use a tool like ILSpy to disassemble .NET binaries and see how they are comprised. – Matthew Jan 01 '13 at 16:37
  • @TheodorosChatzigiannakis: I will Google it surely, but can you please explain the parsing method followed for this specific parser if possible? – Gaurang Jan 01 '13 at 17:51

2 Answers2

3

Here is the relevant code, which you can view under the terms of the MS-RSL.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
  • Great Effort!!! Let's together try and dissect the method systematically. Now, going back to the main question, how does the method understand which numerical value the digit character represents? – Gaurang Jan 02 '13 at 05:17
  • It simply subtracts `'0'` from it. Think about this: We know that `'0' != 0` and that `'5' != 5`. But `'0'` and `'5'` are still numbers, so you can do math on them. And, because `'0'`, `'1'`, `'2'` etc are consecutive, it's guaranteed that `'5' - '0' == 5`. – Theodoros Chatzigiannakis Jan 02 '13 at 09:18
2

"Culture-specific information" refers to the ways numbers can be written in different cultures. For example, in the US, you might write 1 million as:

1,000,000

But other cultures use the comma as a decimal separator, so you might see

1'000'000

or:

1 000 000

or, of course (in any culture):

1000000
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • also allows to convert wierd numbers languages like arabic http://msdn.microsoft.com/en-us/library/xbtzcc4w.aspx – Nahum Jan 01 '13 at 16:49