C# – Convert this abstract class to an interface

abstract classcinterfacesSecurity

I have a security method I would like to be able to sprinkle into other classes throughout my program. It is currently an abstract class but I feel it would be more appropriate as an interface. Can someone help me convert it? I wasn't able to call PrincipalIdentity() the same way I could with it being abstract.

public abstract class SecurityBase {

        public GenericPrincipal PrincipalIdentity() {

            WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

            string authenticationType = windowsIdentity.AuthenticationType;
            string userName = windowsIdentity.Name.Split('\\')[1];;

            GenericIdentity authenticatedGenericIdentity = new GenericIdentity(userName, authenticationType);

            string[] Roles = //generate array;    
            GenericPrincipal pr = new GenericPrincipal(authenticatedGenericIdentity, Roles);

            return pr;
        }
    }

Best Answer

Is there a reason you need this method in your business classes at all? I can't see any reference to this or to other member fields, meaning it's a disconnected utility method that can happily sit in a UserProvider sort of class, a service that is probably orthogonal to your actual business domain.

If you do want to have it as part of your objects, you can simulate implementation inheritance with interfaces using extension methods:

public interface ISecurityEnabled 
{
     // empty marker interface.
}

public static class SecurityExtensions 
{
    public static GenericPrincipal GetPrincipalIdentity
           (this ISecurityEnabled securityEnabledObject)
    {
         // your code here.
    } 
}

This will allow you to call GetPrincipalIdentity on every object that's marked with the ISecurityEnabled interface. If the method actually needs any properties from that object, add them to the ISecurityEnabled interface to have them available in the extension method.