Before I get started on Generic Classes in .Net, I'd like to give credit to CopySourceAsHtml for my new formatting of code blocks in my blog.  I made some of my own enhancements, but I'd still be using the boring black on yellow formatting without CSAH.  To learn how to get it to work on VS2008, go here (be sure to read the comments if you are running on XP).

We've all used generic classes without thinking much about it.  I use List<T> extensively (perhaps abusively).  I really only discovered the power of these classes when I started defining my own.  I was looking at my code and shaking my head over the duplication between my controller classes.  I finally decided to use inheritance and a template method to rid myself of this duplication.  I also introduced a base interface for my view that the base controller would interact with.  With a non-generic implementation, all of the subclasses would have to cast the view to the interfaces they each used.  With generics, no casting is necessary.  Just like List<T>, all of the properties and methods become strongly typed.

    1 public abstract class MyBaseController<T> where T : IMyBaseView
    2 {
    3     protected IMyDataContext _dataContext;
    4     protected T _view;
    6     public virtual void Observe( T view, IMyDataContext dataContext )
    7     {
    8         _view = view;
    9         _dataContext = dataContext;
   11         if( !_view.IsPostBack )
   12         {
   13             PreInitializeView();
   14             InvalidateCache();
   15             InitializeView();
   16         }
   17         else
   18         {
   19             UpdateView();
   20         }
   21         AttachEvents();
   22     }
   23     ...
   24 }

And an example of a concrete controller:

    1 public interface IMyConcreteView : IMyBaseView
    2 {
    3     event EventHandler Added;
    4     event EventHandler Edited;
    5     event EventHandler Deleted;
    6 }
    8 public class MyConcreteController : MyBaseController<IMyConcreteView>
    9 {
   10     protected override void AttachEvents()
   11     {
   12         base.AttachEvents();
   13         _view.Edited += new EventHandler( _view_InvalidationEvent );
   14         _view.Added += new EventHandler( _view_InvalidationEvent );
   15         _view.Deleted += new EventHandler( _view_InvalidationEvent );
   16     }
   17     ...
   18 }

Sure, I could have introduced a local "view" property that casts the base view to my concrete view, but do I really want to do that for all of my controllers.  I'm thankful that generics can do the work for me.

Tags: ,
posted on Monday, July 21, 2008 11:07 AM
Filed Under [ .Net Design C# ]


No comments posted yet.

Post A Comment