Is ToString a Static Method?

87 Views Asked by At

I researched extension methods and found out they are static. I want to know if ToString is a static method?

Because all extension methods are static ... so ToString is a static method too?

2

There are 2 best solutions below

0
Chester Reynolds On

In C#, ToString is an instance method, not a static method.

for example:

int num = 715;
string str = num.ToString();

num is an int type and ToString is called on an instance of the number. ToString is defined in System.Object

0
Dmitry Bychenko On

You can inspect methods (ToString() in your case) with a help of reflection:

using System.Reflection;

... 

// We want to get information about ToString method of object class
// Let's try public and no public methods either instance or static
var methodInfo = typeof(object).GetMethod(
  "ToString",
   BindingFlags.Instance | BindingFlags.Static | 
   BindingFlags.Public | BindingFlags.NonPublic);

if (methodInfo is null)
    Console.WriteLine("Method is not found");
else
    Console.WriteLine(methodInfo.IsStatic ? "Static" : "Instance");

Output:

Instance

So we can conclude, that ToString is a typical instance method of Object class.

Please, fiddle yourself.