Override a static method

You can't override a static method. A static method can't be virtual, since it's not related to an instance of the class.

The "overriden" method in the derived class is actually a new method, unrelated to the one defined in the base class (hence the new keyword).


Doing the following the will allow you to work around the static call. Where you want to use the code take an IRolesService via dependency injection then when you need MockRolesService you can pass that in.

public interface IRolesService
{
    bool IsUserInRole(string username, string rolename);
}

public class RolesService : IRolesService
{
    public bool IsUserInRole(string username, string rolename)
    {
        return Roles.IsUserInRole(username, rolename);
    }
}

public class MockRoleService : IRolesService
{
    public bool IsUserInRole(string username, string rolename)
    {
        return true;
    }
}

You cannot override a static method.

If you think about it, it doesn't really make sense; in order to have virtual dispatch you need an actual instance of an object to check against.

A static method also can't implement an interface; if this class is implementing an IRolesService interface then I would contend that the method should not be static at all. It's better design to have an instance method, so you can swap out your MockRoleService with a real service when you're ready.