3

Studying extension methods using the book as an example of expanding the functional structure of an Int32 (int keyword) in C# (we cannot inherit structures and change the source code in the case of Int32), I realized that extension methods are needed for three things:

  1. If inheritance is not possible, as in the case with sealed classes;
  2. In case of the inability to change the source code;
  3. If it is possible, but undesirable, to change the source code of a class or structure.

I wonder what would be a typical example for the third case.


The question:

When I describe the class myself and I can make changes to it, without using the extension method, but why in this case I might need to use the extension method if I can just change the code in my class?

That is, I ask you to give an example when I can change the code, but this is undesirable and desirable use extension method.

Stefan
  • 17,448
  • 11
  • 60
  • 79
  • 1
    Does this answer your question? [When do you use extension methods, ext. methods vs. inheritance?](https://stackoverflow.com/questions/787324/when-do-you-use-extension-methods-ext-methods-vs-inheritance) – panoskarajohn Jan 05 '20 at 11:37
  • I (again) doubt that this is a dupe; OP asks for a very specific case while the dupe addresses the general case and no answer addresses this specific scenario. Even more; OP already gives the answer to the general cases himself here, but wants to know more in-depth information about a specific case; @HenkHolterman. – Stefan Jan 05 '20 at 19:22

1 Answers1

1

Funny, I just stumbled upon a question where this might apply to.

You are wondering about the case of

why extend if you can modify the source?

There are a lot of scenario's but the base line:

You want to extend if the added functionality is not an intrinsic part of the class

I'll give you an example


Lets say you have a API client. You created C# code to consume this client. Lets call it WebClient

Now, lets say you use this WebClient in another MVC Web API application to fetch remote data. This can be called by a remote user A.

There is a cass in which you'll end up with a situation in which you want to return a specific result to A, from your MVC Web API application based on the result of the WebClient.

This code will be used throughout the MVC Web API Application, so: considering DRY, you want to write it just once.

So, no you have the choice: in the WebClient or not.

Consider this:


The MVC Web API specific functionality is there due to the fact you choose that technology, but it has nothing to do with the intrinsic properties and funtionality of the WebClient.

This would be a typical use case for extension.

See: Duplication of code when on WEB Api validation as my source of inspiration.

Stefan
  • 17,448
  • 11
  • 60
  • 79