Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are "static" and "this" needed for extension methods, and how is their memory allocated?

A few questions about Extension Methods:

  1. Why are Extension Methods static?

  2. Why do they need to be declared in a static class?

  3. What does the this keyword indicate in the parameter list of extension method? As it is a static class how does the "this" keyword work in this context?

  4. How does memory allocation happen for these type of methods?

like image 618
Nishant Avatar asked Apr 20 '11 12:04

Nishant


1 Answers

The only difference between a static and a non-static method is that a non-static method receives an implicit parameter - this. Extension methods are not called in the context of the object on which the method is declared, therefore there is no way to pass them the this reference, therefore they must be static.

You cannot use the keyword this inside an extension method, I hope this answers your third question. The this keyword in the parameter list is there just to indicate which type this method extends.

What is your question about memory allocation? An extension method is just like any other static method, only the call syntax is different.

like image 104
Ilya Kogan Avatar answered Sep 19 '22 04:09

Ilya Kogan