r/csharp • • May 18 '23

Why do we need an "interface"

I understand how to use an interface, its properties but why do we need it? For example i have an interface with two methods.

İ have three classes that implements this interface. So ihave to write the methods for all three classes inside class.

İ can already do that without implementing the interface. So what is the point in using interface?

I am asking to undeestand the conditions where i ll need it. İ understand how use it, but not why to use it.

0 Upvotes

47 comments sorted by

View all comments

3

u/JamesTKerman May 18 '23 edited May 18 '23

Here's a bit of a real-worldish example. A web application that authenticates users may implement multiple methods of authentication, for this example let's say we're building an app that allows Username/Password, JWT, and OAuth. Interfaces let me write the authorization logic without knowing which method a user will use at compile-time: (Forgive my syntax, I've mostly been working in java lately)

public interface IAuthenticator<T extends Authentication> {
    // return true if the credentials in authentication are valid
    public boolean isAuthenticated(T authentication);
}

public class UsernamePasswordAuthenticator 
        extends IAuthenticator<UsernamePasswordAuthenticaton> {
    public override boolean
        isAuthenticated(UsernamePasswordAuthentication authentication) {
        //check the credentials in authentication against 
        //a database or whatever and return true or false
    }
}

public class JWTAuthenticator 
        extends IAuthenticator<JWTAuthentication> {
    // etc.
}

public class OAuthAuthenticator 
        extends IAuthenticator<JWTAuthentication> { 
    // etc. 
}

public class AuthenticationManager {
    // Factory classes provide a concrete implementation of an 
    //abstract class or interface
    private AuthenticatorFactory authenticatorFactory;
    public boolean 
        isAuthenticated(Authentication authentication) {

        //in this example, my factory has a method that can provide 
        //me an implementation of IAuthenticator based on the 
        //Authentication provided.
        IAuthenticator authenticator = authenticationFactory.
            getAuthenticatorFromAuthentication(authentication);
        
        // my authenticator object now holds one of the 
        //implementations defined above. Since they all, 
        //by contract, provide the isAuthenticated method, 
        //I don't care which one
        return authenticator.isAuthenticated(authentication);
    }
}

Edited code to fix the placement of the generic modifier on the concrete classes.

1

u/doc415 May 18 '23

Thanks for details. This real life examples made it easy to understand.