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

后端 未结 5 1229
醉话见心
醉话见心 2020-12-10 05:47

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. <
5条回答
  •  难免孤独
    2020-12-10 06:22

    Why are Extension Methods static?

    Because you cannot modify the class to add instance methods. It's all syntactic sugar to make calls to these methods nicer, nothing more.

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

    Because we're not meant to create instances of the class. It's a design decision. Why complicate things like having instances of some class that has extension methods attached to them that might not even be usable?

    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?

    It's a static method. this has no meaning in this context. The this in the signature is just a way to denote that an extension method is being declared.

    How does memory allocation happen for these type of methods?

    Confused about this one. They are all static methods on a static class. They are "allocated" like any other (static) method, there's only one copy of the code for the type.

提交回复
热议问题