Got more questions? Find advice on: SQL | XML | Regular Expressions | Windows
in Search
Welcome to AspAdvice Sign in | Join | Help

C# Nuggets

Generic best practices

I have become increasingly aware that Generics in C# v2 may be badly used because there have not been any best practice guidelines published. I'll start the ball rolling here by discussing what I consider to be the best usage of generic classes in your own projects:

Never use a generic class directly if you can help it. Always create a new class which derives from the generic class and use that instead. eg:

public List<Author> GetAuthors() {...}
is bad. Whereas,

public class AuthorList : List<Author> {}
public AuthorList GetAuthors() {...}

is good. Why is this? Well, if you subsequently want to add another method such as an aggregating method like
public int AuthorCountFromRussia() {...}
you can't add it directly to the List<Author> type but it would be trivial to add it to your AuthorList class - and this new method could be used everywhere with no code changes!

I've also seen a people recommend the using statement -
using AuthorsList=List<Author>;

but this suffers from the same problem discussed above and is inferior to creating your own custom type.

Published Monday, May 10, 2004 12:51 PM by rbirkby
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Dan said:

That has nothing to do with generics, you face the same question of inheritance vs. inflexible use for a non-generic class as well.
September 11, 2008 10:35 AM

Leave a Comment

(required) 
(optional)
(required) 
Enter the code you see below

Submit