Mar 20

As we’ve seen, we can define generics in interfaces, classes, delegates and methods. In a previous post, I’ve already mentioned that you cannot define generics for properties. Besides properties, you can’t also define generics  for indexers (aka parameterful properties), events, operators, constructors and finalizers. Notice that these members can use eventual generic type parameters defined at interface or class level, but they cannot introduce their own generic type parameters. Here’s an example of what you can’t do:

public class Test {
public Test<T>( ) {

You might be curious to understand why you cannot define generics for these members. I was curious too…the best answer I got pointed to two interesting facts:

  • it seems like there aren’t really many cases where this feature would be needed.
  • allowing it would mean that the languages would have to be redesigned to allow these features.

The best example for understanding this last point relies in understanding how operators are used. For instance,there’s currently no way to specify a generic type with an operator. Lets walk through a simple example:

var str1 = “Hello, “;
var str2 = “there!”;
var str3 = str1 + str2;

We’re adding two strings through the operator+. Suppose we could use generics when defining the operator+. How would we write the code for specifying the generic type? I mean, would this be a good option?

var str1 = “Hello, “;
var str2 = 1;
var str3 = str1 +<Int32> str2;

In my opinion, that wouldn’t really contribute to improve the readability of the code…and that’s it for now. Stay tune for more.

2 comments so far

  1. Przemyslaw
    8:14 am - 3-22-2011

    You cannot create generic attribute either. CLR allows this, but there is no way to create them with c#. Generic attributes are not implemented in c#.

    • luisabreu
      10:33 am - 3-22-2011

      Yes, you’re absolutely right. I forgot about that and I’ll have to update the post to reflect that info. thanks for the correction!