Reputation: 63
One of the questions that i always faced was the implementation of .NET Framework class libraries.
I know some of the methods original implementation:
For example :
MessageBox.Show("...");
As i know this method must have used P/Invoke to call Win32 API.
but something like this:
System.Convert.ToInt32(mystr);
I actually don't know how it works because conversion between int and string is not possible in pure C#.(Can you do exact same thing without using that method? Actually I don't know).
Finally if you know the answer please clarify these concepts for me speicially the 2nd example.
Upvotes: 1
Views: 479
Reputation: 113402
Microsoft has made the BCL available online at: http://referencesource.microsoft.com
Calling Convert.ToInt32(string)
will eventually call int.Parse
, which in turn will eventually call the actual routine on an internal Number
class here:
One of the basic routines listed there is as follows:
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe static Boolean NumberToInt32(ref NumberBuffer number, ref Int32 value) {
Int32 i = number.scale;
if (i > Int32Precision || i < number.precision) {
return false;
}
char * p = number.digits;
Contract.Assert(p != null, "");
Int32 n = 0;
while (--i >= 0) {
if ((UInt32)n > (0x7FFFFFFF / 10)) {
return false;
}
n *= 10;
if (*p != '\0') {
n += (Int32)(*p++ - '0');
}
}
if (number.sign) {
n = -n;
if (n > 0) {
return false;
}
}
else {
if (n < 0) {
return false;
}
}
value = n;
return true;
}
Upvotes: 5
Reputation: 4481
Implementation of MessageBox.Show is here.
Implementation of Convert.ToString is here.
Upvotes: 1
Reputation: 1500515
Can you do exact same thing without using that method? Actually Nope.
You absolutely can. Here's a really inefficient way of doing it - which doesn't consider overflow, invalid input or negative numbers, but demonstrates the general principle.
int ParseStringToInt32(string text)
{
int result = 0;
foreach (char c in text)
{
result = result * 10 + (c - '0');
}
return result;
}
Fundamentally there's nothing mystical about the process of parsing a string as an Int32
. It's just a case of looking at each character, considering its numeric value, and doing some arithmetic.
Indeed, there are times when it's worth doing it manually - in Noda Time we have our own numeric parsing code to allow a limited number of characters to be parsed without having to take a substring.
Upvotes: 6
Reputation: 299
try this: it's not the Microsoft implementation, since it's not open source. but it should give you an idea
Upvotes: 1