So, where can’t I define generics?

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.


~ by Luis Abreu on March 20, 2011.

2 Responses to “So, where can’t I define generics?”

  1. Hi,
    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#.

    • 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!

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

%d bloggers like this: