Why do I have to use the this pointer to call an extension method of the extended class

Updated on October 14, 2016 in [A] C# .Net
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on Reddit0
0 on October 14, 2016

Don’t even ask why I need this, I found an alternative solution. I am now just asking out of curiosity. Just wanted to say it first.

When I make an extension method, let’s say for a MonoBehaviour, I would expect to be able to call it from classes that inherit from it, right? Let me just put the test I did:


public class SomeMonoBehaviour : MonoBehaviour

{

public void Test()

{

TestMethod();

}
}
public static class TestClass

{

public static void TestMethod (this MonoBehaviour target)

{

Debug.Log("TestMethod from TestClass was called!");

}

}

Obviously, as you can tell by the title, TestMethod doesn’t exist, though if I call it like that…


this.TestMethod();

…it works.

So I get “this” is basically an instance, just like any instance I make. But as long as I know, you don’t have to put “this” unless you have a local variable with the same name, but here you do…

It makes the code longer, and it might seem like a little bit, but the reason I made it is that it will be like a keyword (making an extension method to “Object”, the class every class/struct inherits from), so that “this”, or just making a static call kinda ruins it. I tried partial classes, and it works, but Object is not partial, and I can’t trust myself inheriting every singe class from my custom Object.

It isn’t necessary now, I gave up on it now, I was just wondering if anyone on the forum has any logical explanation to why it works like that…

Imagine many lines space (the forum doesn’t support that)
If only C# had macros like in C++……. *Thinks about how awesome it would have been*

  • Liked by
Reply