tags:

views:

37

answers:

1

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?

+3  A: 

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 Enumerable does) but you shouldn't call it Extensions in that case.

You could change it into a genuine extension method on HttpContext, of course:

public static int GetUserId(this HttpContext context)
{
    return (int)Membership.GetUser(context.User.Identity.Name).ProviderUserKey;
}

Then call it as:

int userId = HttpContext.Current.GetUserId();
Jon Skeet
Yes, that's why I quoted 'extension method'. I like both your ideas of not naming the class Extensions, and the HttpContect extension. I'm at a loss which one to try first, hehe.
ProfK