Parameters that implement multiple interfaces

Run the following code:

internal interface IHasLegs
{
    int NumberOfLegs { get; }
}

internal interface IHasName
{
    string Name { get; set; }
}

class Person : IHasLegs, IHasName
{
    public int NumberOfLegs => 2;
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

class Program
{
    static void ShowLegs(IHasLegs i)
    {
        Console.WriteLine($"Something has {i.NumberOfLegs} legs");
    }
    static void Main(string[] args)
    {
        Person p = new Person("Edith Piaf");

        ShowLegs(p);

        Console.ReadKey();
    }
}

      

Is there a way to implement ShowLegs so that it only accepts values ​​that implement IHasLegs and IHasName, without declaring an intermediate name IHasLegsAndHasName: IHasLegs, IHasName? Something like ShowLegs ((IHasLegs, IHasName) i) {}.

+3


source to share


1 answer


static void ShowLegs<T>(T i) where T : IHasLegs, IHasName
{
    Console.WriteLine($"{i.Name} has {i.NumberOfLegs} legs");
}

      



+10


source







All Articles