I've implemented some extension methods and put those in separate Class Library project.
Imagine I have a simple extension method like this in class library called MD.Utility
:
namespace MD.Utility
{
public static class ExtenMethods
{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}
}
But nowhere in the web app like the App_code
folder or the WebFroms code-behind page can I use this extension method. If I do something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MD.Utility;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string email = "[email protected]";
if (email.IsValidEmailAddress())
{
//To do
}
}
}
The compiler doesn't recognize IsValidEmailAddress()
and there's even no IntelliSense support.
While if I put my extension method in the App_Code
folder, it's usable in another .cs
files in the App_code
folder or the WebForms code-behind pages.
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.
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.
An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.
Did you remember to add a reference to your class library in the web project ?
You will need that. Other than that, your code looks fine, and should work.
If changes are not getting recompiled when you do a solution rebuild, then it could be the type of reference you are using. If the MD.Utility project is in your web project solution, you should make the reference a "Project Reference." That will cause the build to consider that code as a dependency and therefore rebuild it when you change something. If you just include it as a DLL, then the DLL is considered external and the build will not consider it, even if it is in the same solution.
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