Home > Back-end >  C#, Finding system's default method's body
C#, Finding system's default method's body

Time:12-20

I just started coding with C# and wondered why there is no body in system-defined classes. for example when you look inside the class System.object the methods like ToString() have no body, see the picture below. Class system.Object

This is where not the class object nor the method ToString is abstract.

CodePudding user response:

The system source code is not available, instead, it has been compiled to byte code. Therefore, since the source code is not available, only definitions are displayed when browsing it in Visual Studio. If you want to see the source code for the .NET library, you can take a look at the reference source.

CodePudding user response:

You're viewing only the metadata of Object class. Here you can check only available fields and methods of this class.

If you check System.Object.ToString() method in a .NET source browser, you can see that ToString() method has its own definition – by default it's name of the class, as comment says.

CodePudding user response:

As Wexos mentions, the system libraries contain byte code (or IL - Intermediate Language code).

You can use reflection to obtain the compiled IL instructions associated with a given method:

var objectClass = typeof(object);
var actualInstructions = objectClass.GetMethod("GetHashCode")
                                    .GetMethodBody()
                                    .GetILAsByteArray();

Now all you need to do is parse the IL instructions :)

  •  Tags:  
  • c#
  • Related