Click here to Skip to main content
15,891,936 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
when should i use interface instead of class?what is d usefullness of using interface
Posted

An interface allows you to specify things that inheriting objects must implement but without you needing to provide any implementation yourself.

Take the IComparable interface used for sorting, there is no way Microsoft could possibly know how to sort you class, but by you providing your own implementation, any of their methods that take an IComparable parameter will be able to sort it!
 
Share this answer
 
You mean usage. Wright?

Here's a very short expalation:

A Interface defines a contract that the
derived class should implement.

Meaning it defines the methods(their signatures) that a class and/or struct should implement.

Also C#/.Net allows for multiple Interface but single class inheritance.

Supose you have a LogSystem. That system should write something.

So:
interface IWrite
{
    public void Write();
}


The interface above defines a contract for the classes.It's contract it's a single method in this case that returns null.

Now you could have like a WriteToLog class, WriteToOutput(e.g. console),
to a DB.

but all of this classes Implement the IWrite interface.

C#
public class WriteToLog: IWrite{
    public void Write(){
       //implement it here
    }
}

public class WriteToConsole: IWrite{
    public void Write(){
       //implement it here
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900