I have an extension method as follows:
public static class PageExtensions
{
public static int GetUserId(this Page targetPage)
{
var user = Membership.GetUser(targetPage.User.Identity.Name);
return (int)user.ProviderUserKey;
}
}
Now in a page I need to use this method in a static WebMethod, so I have added another ‘extension method’ to PageExtensions:
public static int GetUserId()
{
return (int)Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey;
}
and I call it as follows in my WebMethod:
PageExtensions.GetUserId()
Is this a good way of doing things? Are there any other ways?
No, you haven’t created another extension method – you’ve created a plain static method.
I would personally separate those out into a class other than “extensions” – it’s clearly not an extension method. It’s not too bad for a static class to have extension methods and non-extensions methods (like
Enumerabledoes) but you shouldn’t call itExtensionsin that case.You could change it into a genuine extension method on
HttpContext, of course:Then call it as: