Twenty
Twenty

Reputation: 5961

Generic constrain for Lists and Collections

I have a Generic method which looks something like this:

public int GetCount<T>(T collection) where T: ICollection
{
   return collection.Count;    
}

Now I want to be able to call this method where the collection parameter can be a List<T> or a HashSet<T>. The current code doesn't fulfill that since the parameters I want to pass do not inherit the ICollection interface. Now would there be any way I could achieve that with a simple constrain?

Upvotes: 2

Views: 1048

Answers (1)

Gleb
Gleb

Reputation: 82

Why don't:

public int GetCount<T>(ICollection<T> collection)
{
   return collection.Count;    
}

Upvotes: 5

Related Questions