Search code examples
c#.netpinvokefcl

How does .NET framework low level APIs work?


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.


Solution

  • 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.