Skip to content

C# Dependency Inversion - Example

This example looks at creating a carpet object. This object can be either "swept" or "exhibited" (e.g. a persian carpet displayed as a wall hanging). To manage this the Carpet class will have a list of actions that can be performed on it.

The carpet class

By defining the action as an interface the code is not dependent on a concrete class.

public class Carpet 
{
    public List<IAction> Actions = new List<IAction>();

    public Carpet(params IAction[] possibleActions) 
    {
        this.Actions.AddRange(possibleActions);
    }

    public PerformActions() 
    {
        foreach(IAction action in Actions) 
        {
            action.PerformActions();
        }
    }
}

The actions

Any action is specified as inheriting from the Action Interface....

public interface IAction 
{
    void PerformAction();
}

The possible actions

public class Sweepable : IAction 
{
    public void PerformAction() 
    {
        // do sweeping stuff
    }
}

public class ArtExhibit : IAction 
{
    public void PerformAction() 
    {
        // do exhibiting stuff
    }
}

Putting it all together

public void CarpetExample() 
{
    var sweeper = new Sweepable();
    var gallery = new ArtExhibit();
    var wallart = new Carpet(sweeper, gallery);
    wallart.PerformActions();
}