Thoughts on C# Generic Constraints

A teammate and I were musing about generic constraints the other day, comparing them to checked exceptions in Java.  So I found it amusing that Jeremy Miller came to the same point with Scott Allen yesterday:

Question of the Day — What’s Worse?generic constraints, or checked exceptions [in java]?

Wouldn’t it be nice if we could “break the chain” of constraints at some point, when the calling code ceases to care?  Since I don’t know of a pattern for that, is there something we can do to minimize the constraint pain?

What about the case where the constraint is there only for the convenience of the implementation; say, being able to call “new T()”?

For example:

T Find<T>(int id) where T : Entity, new()
  var result = new T();
  ...// something to do with the Entity type
  return result;

So now, we have this “new()” constraint all over.  Yuck!  Is “Activator.CreateInstance()” really that hard to type?  I understand that “new T()” reads a lot nicer… but that’s one line of code vs. however many consumers now muddied.

Of course, you might say the “Entity” constraint is just as arbitrary to the calling code (more so as you go up the stack).  However, that constraint helps us do something meaningful, but we can live without the “new(),” which provides no real value.

So considering we’re stuck with the current compiler behavior for now, I’d suggest using constraints more to add value to the interface, and less for shortcuts in the one instance of code.  The downside, in the case of “new()”, is that we won’t know about a missing default constructor until run time, but that should be during the unit tests, which run on every build, right?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s