When/Why would I use an extension method in VB.Net?

255 views Asked by At

I'm new to VB.Net, and I am curious about the use cases for extension methods. Specifically, why would I use an extension method when I have inheritance and interfaces at my disposal? At first glance, extension methods don't seem to me like a very OO practice, and it seems like they would lead to less readable code as opposed to using subclasses and/or interfaces to achieve the same purpose. Is there something special about extension methods that I'm missing? When do you use them?

2

There are 2 answers

0
The_Black_Smurf On BEST ANSWER

Before implementing an extension method, people should always try to see if it could fit inside a standard OO class.

However, there's 2 situations I can think of where those extension may be very handy:

1) Extension of primitive type: You don't want to derive a primitive type (like Int or Date) just to add an method to it. I'm not even sure if you're allowed to derive a primitive type but even if you could, it doesn't mean that you should.

2) Extension of common object: Let's say you want to write some addons functionalities to a very common object; let's say add a ToJSON method to a DbDataReader. You may force users the use your derived Type of DbDataReader (CustomDbDataReader) but they would have to change the code all over the place to use your new class. Using an extension would allow them to use your new method on a native DbDataReader.

You'll also notice that the DbDataReader is an abstract class. SqlDataReader and OleDbDataReader both derive from the DbDataReader class. If you want to write a legit OO function, you would have to write one for SqlDataReader and another one for the OleDbDataReader, even if the function does exactly the same thing.

0
Markus On

You are right that extension methods are not a very important tool in the OO-toolbox. So you might not use them very often to extend classes in your own code.

As you also write, they might lead to confusion when reading other developers' code because you can only use extension methods that are located in a namespace that you have imported.

Nevertheless, extension methods are very handy if you want to create helper methods that extend classes that you cannot change. That is the main use case extension methods are created for.