Maxime
Maxime

Reputation: 1325

How can I use a marker attribute instead of a marker interface?

I have read a lot of things about how marker interfaces are bad (or not, it does not seem so clear).

I do not really understand how Marker Attributes work, and I have created a small example to illustrate my issues:

I have an interface to define Robot, and an other one to define Ninja. It turns out that it exists a classFoo that can multiply stuff, but only with the help of someone which is both a RobotAND a Ninja.

using System;

public class Program
{
    public static void Main()
    {
        IRobotNinja robotNinja = new RobotNinjaAlways10();
        Foo foo = new Foo();
        Console.WriteLine(foo.Multiply(1, 1, robotNinja));
    }
}

public class Foo
{
    public int Multiply(int leftOperand, int rightOperand, IRobotNinja robotNinja)
    {
        return leftOperand * rightOperand * robotNinja.availableShuriken * robotNinja.batteryLevel;
    }
}

public interface IRobot
{
    int batteryLevel
    {
        get;
    }
}

public interface INinja
{
    int availableShuriken
    {
        get;
    }
}

public interface IRobotNinja : IRobot, INinja
{
}

public class RobotNinjaAlways10 : IRobotNinja
{
    public int batteryLevel
    {
        get
        {
            return 10;
        }
    }

    public int availableShuriken
    {
        get
        {
            return 10;
        }
    }
}

It is my understanding that IRobotNinja is a marker class: it has no members.

How can I get the same thing (and in particular, ensuring at compile time that only a Robot/Ninja will help with the Multiply?

Upvotes: 1

Views: 270

Answers (1)

vc 74
vc 74

Reputation: 38179

To avoid creating another interface, you can make Multiply generic with constraints:

public class Foo
{
    public int Multiply<T>(int leftOperand, int rightOperand, T robotNinja)
         where T : IRobot, INinja
    {
        return leftOperand * rightOperand * robotNinja.availableShuriken
                           * robotNinja.batteryLevel;
    }
}

Upvotes: 4

Related Questions