Object Oriented Programming

Interfaces in C#

An interface provides a framework for a class. It gives method signatures and constants to the class to be implemented. A class that uses an interface implements the interface.


Syntax
modifier interface interfaceName {
    //constant declarations    
    //method signatures
}

modifer class className : interfaceName {
   //methods from the interface
}; 

Notes

An interface only contains method signatures and constants, which means it contains no implementation code. All method signatures must be given implementation in any class that implements the interface.

Anything within an interface is implicitly public, unless specified with a modifier.


Example
public interface Country {
    //all classes that implement Country must have the method getCapital()
    public string getCapital(); 
} 
 
public class NACountry : Country {
    string capitalCity;    
    public NACountry(string capitalCity) {
        this.capitalCity = capitalCity;        
    }    

    public string getCapital(){ //implemented method signature from the interface
        return capitalCity;
    }
} 

See Also
Related

Inheritance

Documentation

Interfaces (C# Programming Guide) - MSDN

Add to Slack

< Instantiation   |   Abstract Methods and Classes >

© 2019 SyntaxDB. All Rights Reserved.