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?
When/Why would I use an extension method in VB.Net?
326 views Asked by Sam Hazleton At
2
There are 2 answers
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.
Related Questions in VB.NET
- how do i stop system stack overflow in visual basic?
- Finding and Using Camera found in “Imaging Devices” in VB.NET
- Finding a specific colour within a bitmap range - VB.net 2022
- Filtering a double value
- How to call late bound extension method from VB.NET (Framework)
- Accessing a variable from a string
- Calling ToString with a nominated format returns Char rather than String
- Monthly attendance report in Crystal Report
- Progress Bar increment while running
- GetValue for Field contains too many arguments
- Icon of Window form application
- vb.net connection string to a regular google drive
- VB.NET how to check if a form already exists?
- How to get paste to work for pasting in text in a textbox?
- How to convert base64 string to image using vb.net
Related Questions in OOP
- How do I apply the interface concept with the base-class in design?
- Creating multiple instances of a class with different initializing values in Flutter
- System.InvalidCastException while inheriting a class
- How to add logging to an abstract class in php
- creating cutscenes using OOP and pygame
- What effect does the `virtual` modifier have on an interface member?
- How to pass the value of a function of one class to a function of another with the @property decorator
- Creating a C++ Class Instance for every server request?
- Dart OOP programming
- Containing Object Design
- Clean architecture/OOP and optimization: how to organize for classes with same logic
- How to get 5 LEVEL hierarchy users from database using PHP and MYSQL
- TypeError: unsupported operand type(s) for /: 'property' and 'complex'
- How can I refer to this metaclass inside a metaclass without specifying its name in the code?
- Why customed "-eq" do twice in Powershell?
Related Questions in INHERITANCE
- System.InvalidCastException while inheriting a class
- What effect does the `virtual` modifier have on an interface member?
- Is it allowed to pass "this" of derived class to constructor of base class?
- Why parent no-arg constructor is called?
- Python super().__init__() doesn't call multiple inherited classes?
- How to query child models from parent model data?
- .NET Core : disable parent application web.config inheritance
- Is it appropriate to subclass the parent's parameters in subclass __init__'s within python?
- Inheritance - is it possible to 'force' variable values relative to the derived class?
- Need more parameters in subclass overridden method
- How to call a method on a generic type from inside the generic class?
- Dependency Injection with Generic Interface and Inheritance
- Sparx Enterprise Architect - sysml - how to model a configuration on a block definition diagram using specialization
- Generic "Create" method in .NET Core that creates two entities
- crud operation and function with a an abstract class of which it had two subclasses
Related Questions in INTERFACE
- How do I apply the interface concept with the base-class in design?
- Save Interface in DB golang
- Collections.max with custom Comparator on list
- Linux Networking - Routing packets from one network interface to another
- How to design the file operation interface involving status and transactions?
- Angular component's interface ( @Output / @Input ) how do you expose methods? Or certain type of events?
- Own Pattern / framework for interfacing with components in C
- Does anyone know how to make iPad layout the same as iPhone's? Size wise the text and overall layout get's smaller when I run the app on the iPad
- Use Interface Type in Map or Struct Definition, but Implement with Concrete utype
- How does variance work when implementing interfaces/type aliases in TypeScript?
- Fatal error: Uncaught TypeError when returning class instead of interface
- Golang Use of array of structs that implement MyInterface as []MyInterface not allowed
- Calling c++ from fortran
- Interface and model in TypeScript (angular 17)
- Interface called Delegate call failed
Related Questions in EXTENSION-METHODS
- How to call late bound extension method from VB.NET (Framework)
- How to get correct IServiceProvider instance in my extension method
- Sending messages between two chrome background scripts
- In C#, How can an interface (such as ILogger), with 1 method signature for log(), show 5 on intellisense?
- How to create an extension method overshadowing the regular LINQ extensions?
- Redeclare "==" operator inside an extension type - Dart
- how to overload an extension method that is doing the same thing but different arguments
- Xcode Source Editor option not shown in Extensions
- Use a protocol rather than a struct as an (optional array) extension?
- Is ToString a Static Method?
- Accidental Overrides when trying to provide operators for a type in a context
- 'IServiceCollection' does not contain a definition for 'CustomMethod' and no accessible extension method 'CustomMethod'
- How to create database software with custom extension to save and reload later with C# WinForm App
- How do I use the extension functions for BigDecimal in kotlin?
- Is there way to make extensions polymorphic?
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
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.