C# Interface Types

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

Interface

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

Example

Let's look at a simple program that defines an interface named IPerl, which requires one void Read method. Then, we define 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.

Overview: This C# tutorial shows interfaces. It provides sample code. It explains interfaces in depth.

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
Interface example (IPerl)

Key point: When a class implements an interface, it can be used through a reference to that interface.

Example 2

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 content

Overview. 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().

Method call

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

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 Examples TryGetValue Method

Naming convention

.NET Framework information

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

Encode behavior

Code Complete

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

Complexity

Much of the complexity in software is due to "non-essential" difficulties such as the bugs left behind by other programmers from years ago. However, in some cases, a program has essential complexity, and the object-orientation shown here is essential because 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 orignal problem's complexity.

Accidental complexity Complexity in software that occurs because of poor design choices.

Properties

Property (Icon copyright Microsoft)

You can also use properties (getters and setters) with interfaces in the C# language. The article provided here demonstrates the usage of properties on an interface declaration.

Interface Property

Indexers. How can you use an interface with an indexer property? The article linked here shows you how to use these language features together.

Indexer Interface Use

Specific interfaces

This section provides information

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 Example

Base 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

Performance

Virtual keyword

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 Keyword

Interface 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 Performance

Tip: The absolute performance loss with the interface method is very tiny, often less than a nanosecond. Make sure the big picture of objects in your program is correct before thinking about optimizations.

Summary

The C# programming language

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.

Dot Net Perls