Interface Basics
suggest changeAn interface is a “contract” of functionality. It declares properties and methods, but it doesn’t implement them.
So, unlike classes, interfaces:
- Can’t be instantiated
- Can’t have any functionality
- Can only contain methods * (Properties and Events are methods internally)
- Inheriting an interface is called “Implementing”
- You can inherit from 1 class, but you can “Implement” multiple Interfaces
C# 8 can give an interface method a default body. The points above describe an interface with no default bodies.
public interface ICanDoThis{
void TheThingICanDo();
int SomeValueProperty { get; set; }
}
Things to notice:
- The “I” prefix is a naming convention used for interfaces.
- The function body is replaced with a semicolon “;”.
- Properties are also allowed because internally they are also methods
public class MyClass : ICanDoThis {
public void TheThingICanDo(){
// do the thing
}
public int SomeValueProperty { get; set; }
public int SomeValueNotImplementingAnything { get; set; }
}
ICanDoThis obj = new MyClass();
// ok
obj.TheThingICanDo();
// ok
obj.SomeValueProperty = 5;
// Error, this member doesn't exist in the interface
obj.SomeValueNotImplementingAnything = 5;
// to reach a class member, cast the reference to that class
((MyClass)obj).SomeValueNotImplementingAnything = 5; // ok
This is especially useful when you’re working with UI frameworks such as WinForms or WPF because a custom control has to inherit a framework base class, and you lose the ability to use one shared base class for different control types. An example:
public class MyTextBlock : TextBlock {
public void SetText(string str){
this.Text = str;
}
}
public class MyButton : Button {
public void SetText(string str){
this.Content = str;
}
}
The problem is that both contain some concept of “Text” but the property names differ. And you can’t create an abstract base class for both, because each one already has to inherit a different framework class. An interface can alleviate that.
public interface ITextControl{
void SetText(string str);
}
public class MyTextBlock : TextBlock, ITextControl {
public void SetText(string str){
this.Text = str;
}
}
public class MyButton : Button, ITextControl {
public void SetText(string str){
this.Content = str;
}
public int Clicks { get; set; }
}
Now MyButton and MyTextBlock are interchangeable.
var controls = new List<ITextControl>{
new MyTextBlock(),
new MyButton()
};
foreach(var ctrl in controls){
ctrl.SetText("This text will be applied to both controls despite them being different");
// Compiler Error, no such member in interface
ctrl.Clicks = 0;
// InvalidCastException when ctrl is a MyTextBlock, not a MyButton
((MyButton)ctrl).Clicks = 0;
/* the solution is to check the type first.
This is usually considered bad practice since
it's a symptom of poor abstraction */
var button = ctrl as MyButton;
if(button != null)
button.Clicks = 0; // no errors
}