9.0 Interfaces
FIle Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
Interfaces
Right click on the project, go to Add > New Item
Choose Interface
It is customary to name your interface with a capital I, and then a capital for the first letter in the name i.e.
ITransactions
Discussion
Interfaces make it easier to maintain a program, especially bigger programs. Interfaces are used to fulfill promises throughout your other classes. Within your interface you will only declare the methods, properties, and events, but you will not do any real implementation until you get to the class. When you get to the class that inherits from the interface, then you will implement exactly what you want your methods, properties, and events to do.
The interface defines the what part of the syntactical contract and the deriving classes define the how part of the syntactical contract.
Within C#, an interface can be defined by using the keyword, interface
. For example, the following is an interface for providing transactions:
We defined the interface by typing
public interface ITransactions
. It is customary to name your interfaces with capitol I to begin the name.Within our interface we declared any methods, properties, or events we want to promise our future classes to uphold. In this case we want 2 methods,
showTransaction()
andgetAmount()
.We made our Transaction class and implemented the interface by typing
public class Transaction : ITransaction
.You should then be able press
CTRL .
to stub out the methods needed to fulfill the promises from your interface.Lastly, we implemented the
showTransaction()
andgetAmount()
methods with what we wanted them to do.
This is smaller example, but once you get into larger scale applications, interfaces can make it much more manageable and faster figuring out what your classes need to get your application to run smoothly and efficiently.
Interfaces can also inherit from other interfaces. Take a look at this example and see how the relationship works:
We have three different interfaces:
IPerson1
,IPerson2
,IPerson3
IPerson2
inherits fromIPerson1
The class
Person
inherits fromIPerson2
which also inherits fromIPerson1
. So the promises it has to fulfill areStateLastName()
andStateName()
.Class
Paul
inherits from classPerson
and interfaceIPerson3
. So the promise it has to fulfill isStateAwesome()
.Can you see how interfaces can keep your code more organized and readable?
Helpful Links
Next: Rules
Last updated