So this is episode 1 of a series of blog posts I will be writing on things I could not figure out for the longest time, only to have an “ohhh moment” followed by a “seriously? it’s that easy?” moment.
The first moment I will be describing occurred to me about a month or two ago when I finally understood how to use a generic interface.
I had sort of captured the idea of interfaces by that point—that it’s basically like a binding contract that says ,if you implement me in a class, then you are required to have these methods. Feel free to write whatever you want IN those methods, just make sure they are there.
The one part I could not figure out was how to create and use generic interfaces. I kept seeing examples that included <T> and every time I’d try to use T as a placeholder object, I’d get an error that it wasn’t a defined type. I then thought the T was simply something internet writers used to describe a placeholder, and that it didn’t actually work in code.
It wasn’t until my “ohh” moment that I realized that in order to use the T placeholder, you had to define it in the interface declaration. So, it’d look something like this:
interface IHaveAddedProperties<T>
{
void FormatWithAddedProperties(List<T> myListOfItems);
List<T> ReturnWithAddedProperties(List<T> myListOfItems);
}
The key part was that it was defined as IHaveAddedProperties<T>
Then I could use T inside the method declarations and it worked just fine.
When I implemented the interfaces, across about 15 classes, I simply used it like:
public class myClass : IHaveAddedProperties<myClass>
Now, when the interface is implemented inside that class, it generates the methods
with myClass instead of <T>.
So that was my “seroiusly? it’s that easy?” moment, episode 1.
I’ll be sure to share more with you as time goes on.
Update: If you already have a pretty well defined class, you obviously don’t want to add <T> to your class definition, because that would basically break its implementation everywhere.
So, if you need to have just one method use a generic inside a class, you can do it like this:
public static void PullItemsFromCache<T>(int recordID) where T : class
The last part is optional (where T : something). I indicated that it should be a class in my example, but you could use a specific object, a struct, etc. The point of this example is to show how to implement a generic type inside a single method. You add the <T> to the end of the method name declaration. It’s that easy.