Array Class Collections File String .NET Algorithm ASP.NET Cast Compression Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method Number Regex Sort StringBuilder Struct Switch Time Value Windows

Interfaces contain methods. They can be used across many different classes. It becomes possible to call the methods through the interface reference. Extra code to handle different class types is unnecessary. This simplifies programs. It makes programs more compact and easier to maintain.
An interface defines a contract. Hejlsberg et al., p. 561
This program defines an interface named IPerl, which requires one void Read method. It defines a class named Test, which implements IPerl. This means it must implement the Read method. In the Main method, we create a Test instance and store it in an IPerl reference. Then we invoke the Read method from the interface.
Program that uses interface [C#]
using System;
interface IPerl
{
void Read();
}
class Test : IPerl
{
public void Read()
{
Console.WriteLine("Read");
}
}
class Program
{
static void Main()
{
IPerl perl = new Test(); // Create instance.
perl.Read(); // Call method on interface.
}
}
Output
Read
Key point: When a class implements an interface, it can be used through a reference to that interface.

Next we see how interfaces can be used in collections. This program defines an interface and then two classes that implement that interface. It then creates a Dictionary and populates it with values based on the IValue interface defined. Then, we use string keys to lookup values in the collection and then the execution engine invokes the type-based implementation.
Important: No if-statements or switch-statements are required to select the best method implementation based on the value.
Program that uses interface implementations [C#]
using System;
using System.Collections.Generic;
interface IValue
{
void Render();
}
class Content : IValue
{
public void Render()
{
Console.WriteLine("Render content");
}
}
class Image : IValue
{
public void Render()
{
Console.WriteLine("Render image");
}
}
class Program
{
static void Main()
{
// Add three objects that implement the interface.
var dictionary = new Dictionary<string, IValue>();
dictionary.Add("cat1.png", new Image());
dictionary.Add("image1.png", new Image());
dictionary.Add("home.html", new Content());
// Lookup interface objects and call implementations.
IValue value;
if (dictionary.TryGetValue("cat1.png", out value))
{
value.Render(); // Image.Render
}
if (dictionary.TryGetValue("home.html", out value))
{
value.Render(); // Content.Render
}
}
}
Output
Render image
Render contentOverview. In the first part of the program after the using-directives, an interface named IValue with a single method is defined. All types that implement this interface must then has a member with the identifier and signature Render().

Key point: When the Render() method is invoked on an interface reference, a different one will be chosen depending on the program's internal state at that point.
Content and Image. The program next shows two implementations of the IValue interface, one for Content objects and one for Image objects. Each of these classes uses the colon (:) syntax to specify the IValue interface, and then provides the required public void Render() method with a method body.

Main method. The program has a Main method that serves as the application's entry point. In the Main method, a new Dictionary is created and is populated with three key/value pairs. The key is a string and the value is either Content or Image, which are classes that implement the IValue interface. You cannot create a new IValue(); instead, you must create instances of objects that implement that interface.
Finally in the program, the Dictionary type's TryGetValue method is called. The program takes string literals and then executes the object's method based on its type. You do not need to specify the type of the implementation. The type is known by the runtime at all times, even though not by the source code.
Dictionary TryGetValue
Interface types are usually named with a first letter of I. There is no language-based constraint on this. Instead, this is a convention and as usual with conventions, some experts love it and others hate it. You can read more about interface naming conventions in the book .NET Framework Design Guidelines.
Framework Design Guidelines
In the book Code Complete, Steve McConnell describes many ways the execution of a program can be modeled on the instances of data in memory. Some techniques use type codes and enumerations, while object-orientation uses the actual type of the object as part of the data. This type can then help the compiler with correctness checking. In this way, the interface implementation here encodes behavior in the data while retaining the compiler's useful checks.
Code Complete: Book Review
Much of the complexity in software is due to "non-essential" difficulties such as the bugs left behind by other programmers from years ago. But a program sometimes has essential complexity, and the object-orientation shown here is essential—the selection of what method to invoke must always be made. The example does not promote accidental complexity.
Essential complexity:
Complexity in software that occurs because of the original problem's complexity.
Accidental complexity:
Complexity in software that occurs because of poor design choices.

Let's look at how can you can specify properties on an interface. The syntax for the property type on the interface declaration is somewhat different and could be unfamiliar to you. Also, the interface declarations do not include accessibility modifiers such as "public", but the classes that implement the properties must include those modifiers. Recall that interface accesses may perform a virtual method dispatch, so the method calls are somewhat more expensive.
Property IndexerProgram that uses properties on interface [C#]
using System;
interface IValue
{
int Count { get; set; } // Property interface
string Name { get; set; } // Property interface
}
class Image : IValue // Implements interface
{
public int Count // Property implementation
{
get;
set;
}
string _name;
public string Name // Property implementation
{
get { return this._name; }
set { this._name = value; }
}
}
class Article : IValue // Implements interface
{
public int Count // Property implementation
{
get;
set;
}
string _name;
public string Name // Property implementation
{
get { return this._name; }
set { this._name = value.ToUpper(); }
}
}
class Program
{
static void Main()
{
IValue value1 = new Image();
IValue value2 = new Article();
value1.Count++; // Access int property on interface
value2.Count++; // Increment
value1.Name = "Mona Lisa"; // Use setter on interface
value2.Name = "Resignation"; // Set
Console.WriteLine(value1.Name); // Use getter on interface
Console.WriteLine(value2.Name); // Get
}
}
Output
Mona Lisa
RESIGNATION
Description. The program contains one interface type definition. The interface IValue is a contract that requires implementations to have two properties, a Count property of type int and a Name property of type string. You can see how the properties in the interface itself simply use empty get; and set; statements.
Classes. The program also includes two classes that implement the IValue interface in a slightly different way. The classes contain regular properties, as you see in any class. The Name property uses an explicit backing store field, while the Count property is automatically implemented. The Main entry point then accesses the property implementations through the interface type.
Main MethodNote: Interfaces that stipulate properties can use empty get; and set; statements in curly parenthesis in the interface definition. The properties themselves cannot have method bodies in the interface definition. Instead, you can implement the interface in classes and use regular properties with the same names there.

Continuing on, we show some of the most important interfaces in the .NET Framework. The IEnumerable interface is used with many collections and also with LINQ. The IList interface is a generic interface that is implemented by arrays and the List type.
IEnumerable IDictionary IList IComparable IEnumerable Array ExampleBase interfaces. You can use the mathematical concept of transitive closure to understand what set of interfaces form the base interfaces. This can help with understanding type hierarchies in object-oriented languages.
Transitive Closure
In many benchmarks, using a simple switch statement will perform a tiny bit better than using virtual methods. However, the switch statement may grow in size and reduce performance. Additionally, the non-object oriented approach may increase complexity over the project's lifecycle and require more debugging code, which will actually reduce performance.
Sealed KeywordInterface versus virtual. You have the option of using interfaces or virtual methods in some programs. Which version is faster? In this article, we benchmark interfaces against virtual methods, providing data about which is more efficient in the virtual execution engine.
Interface Versus Virtual Method PerformanceTip: The absolute performance loss with the interface method is tiny, often less than a nanosecond. Make sure the big picture of objects in your program is correct before thinking about optimizations.

We examined interfaces and how they are implemented with other classes. The runtime selects the interface implementation during execution without having it specified in the source code. The type system is used encode behavior as data.