Using Generics with Interfaces in C#

I wanted to create an interface; however one of the methods I wanted to implement in it had a class as a parameter. I thought about it and realized that be doing so I would be tightly binding my interface to a specific class. I didn’t think that was good practice because interfaces need to be implemented into any class that needs it, regardless of if it will use the specific class in a method. So I searched around and found, again, the lovely Generics.

I was able to write my generic interface like this.

public interface IGuitar<t>
{
     string Name { get; set; }
     string GetBodyStyle(T t);
}

You see the method I implement in the Interface is not bound to a specific class. Instead it will be bound to the class it gets passed.

I implemented the generic interface like below. I was now able to create any type of guitar I wanted using my generic interface and would always be certain that it would have a method called GetBodyStyle and a Name.

public class ElectricGuitar : IGuitar<electricguitar>
    {
        public string Name { get; set; }
        public string GetBodyStyle(ElectricGuitar t)
        {
            return "The electric guitar is: " + t.Name;
        }
    }

Implementing is no problem. In my program I create an instance of my class and then set the Name. Then anywhere I needed the name I could call the GetBodyStyle() method.

ElectricGuitar eGuitar = new ElectricGuitar();
eGuitar.Name = "Les Paul Style";
Console.WriteLine(eGuitar.GetBodyStyle(eGuitar));

Download the source