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.?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With