Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird extension method issue with inheritance

I'm trying to extend Page class to add some new functionality (ease of use for some methods as they will be called directly within the code of that page) in ASP.NET, and I'm getting a weird error:

My method is called SetQuery,
if I type SetQuery in a Page class, it is not recognized (yes, I've added using [Namespace];),
if I type base.SetQuery it is seen in IntelliSense, but doesn't compile saying no method or extension method is actually found in Page,
if I type (this as Page).SetQuery it is recognized and works.

Especially the second case seems to be a bug to me, as IntelliSense recognizes it as an extension method, but no compilation.

Is there any 'more natural' way to type SetQuery as I go, without casts etc.?

like image 440
Can Poyrazoğlu Avatar asked Jul 31 '11 09:07

Can Poyrazoğlu


People also ask

When would you not use an extension method?

When you're not sure which Type is the one to extend, don't use extension methods. For example, to build a house from brick and mortar I can extend brick with brick.

What is extension method in OOP?

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 extension method in C++?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.


1 Answers

Extension methods always require an (explicit) target object, so it is impossible to call an extension method via just TheMethodName(). I suspect that if you type:

this.SetQuery();

it will work. There is never an implicit this. with extension methods. Odd but true.

The above explains why SetQuery() doesn't work; base.SetQuery() won't work, since the extension method is defined for Page, not for the base-class. (this as Page).SetQuery() will work for the same reasons as this.SetQuery(), and actually since this as Page is obviously true, the compiler will treat that as a no-op - i.e. this.SetQuery() and (this as Page).SetQuery() should generate the same IL (as long as the actual page doesn't have a more specific SetQuery() method, obviously).

like image 76
Marc Gravell Avatar answered Sep 28 '22 07:09

Marc Gravell