Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Extension Methods inline in an ASPX page?

Is it possible to do something like this inline in an ASPX page?

<%= Me.SomeExtensionMethod() %>

I can't seem to figure out how to get this to work properly. I'm receiving an error saying that "SomeExtensionMethod" is not a member of the current Page object. I've added the necessary <%@ Import Namespace="..." %> directive at the top of my page. This Does work in code-behind.

This isn't vitally important, but it would be good to know how to do in the future.

Thanks!

like image 427
Mark Carpenter Avatar asked Jan 15 '10 19:01

Mark Carpenter


People also ask

Can we write extension method for interface?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

Where we can use extension method in C#?

C# extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Should I use extension methods C#?

Extension methods are an excellent addition to the C# language. They enable us to write nicer, more readable code. They allow for more functionally styled programming, which is very much needed in an object-oriented language. They also should be used with care.

Can we write extension method for static class?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface.


2 Answers

Adding imports in the namespace works for me!

<%@ Import Namespace="Foo.FooFoo" %>
like image 134
Sector0 Avatar answered Sep 28 '22 01:09

Sector0


Try closing the .aspx page and opening it up again as per this answer. If that improves things at all (e.g. enable intellisense) but doesn't solve it, please post any new errors you get.

You could also add the Public modifier to your Module or class definition. If you're using Modules, it really doesn't make sense to me that it would be required, but some discussion on this forum indicates that it might help.

like image 10
Michael Haren Avatar answered Oct 01 '22 01:10

Michael Haren