Monday, July 27, 2009

Sometimes I amaze even myself!

I built a generic method in C#. One of the parameters to the method was the generic type <T>

Looking at my method, I created some instances of T using the new keyword/operator.

I thought to myself, "some classes don't have a constructor... I'll need to restrict that in the declaration. Something like
private static long CreateInstances<T>(List<T> instanceCollection) where T "has a default constructor" {...}


I looked up the where contextual keyword and learned that the syntax for what I wanted to do was:
private static long CreateInstances<T>(List<T> instanceCollection) where T: new() {...}


Just before I hit that last parenthesis I noticed the red-squiggle. It was under some code down in the method body that used the type 'T'

T variable = new T();


I hovered over the squiggled text to see what was the matter:
Error: Cannot create an instance of the variable type 'T' because it does not have the new() constraint.


Ha!! I defeated the red-squiggle before I had even seen it!

No comments: