Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods - Changing the Namespace

Tags:

c#

I'm using a third party library which contains a bunch of extension methods on top of IQueryable. To use these extension methods i don't wish to have my application littered with using statements to the third party namespace in which the extension method resides in.

This is so that i can switch it out the library sometime in the near future as easily as possible. However i'm not sure what's the best way of doing this. One option i did contemplate was to create my own set of extension methods within the project (then i can control the namespace). The problem with this is i can't see how i can maintain the name of the existing extension method. For example:

namespace MyProject.Extensions {
    public static class IQueryableExtension {
        public static IQueryable<T> Fetch<T, K>(this IQueryable<T> queryable, Expression<Func<T, K>> selector) {
            return queryable.Fetch(selector);
        }
    }
}

You may see the problem here. Where i am trying to call the third party extension method within mine it actually calls itself creating an infinite loop.

I'd appreciate the help. Thanks

like image 825
nfplee Avatar asked Aug 18 '11 11:08

nfplee


People also ask

What namespace can you use when you write an extension method?

Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions , they'll all be brought into scope by the using Extensions; directive.

What is correct extension method?

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.

What is an advantage of using extension methods?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.

What are extension methods explain with an example?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.


1 Answers

You don't have to use extension methods as extension methods, you can use them like static methods... so you could call the 3rd party Fetch method:

ThirdPartyNamespace.Fetch(queryable, selector)
like image 113
Martin Booth Avatar answered Oct 11 '22 16:10

Martin Booth