This is a mirror of official site: http://jasper-net.blogspot.com/

Generics and Attributes

| Tuesday, July 12, 2011
I really like attributes in .NET. So much so that I co-authored a book on them a long time ago. The only thing that's been kind of annoying is that custom attributes don't support generics ... at least I thought they didn't until today. I ran across this article and I found out you can use generics with attributes, but you can only do it at the IL level. Now, there's a number of things I know you can do in IL that aren't available in languages like C# and VB, and even if you try to define stuff in IL you can't consume it in C# (like overloading methods by return type only), but thankfully generic attributes are consumable in "normal" .NET languages! Here's a simple example on how you can do this.

Let's say you want to have a generic attribute like this:

[AttributeUsage(AttributeTargets.Class)]
public abstract class MyGenericAttribute<T> : Attribute
{
  protected MyGenericAttribute();

  public abstract void Consume(T target);
}

Rather than trying to figure out the IL by hand, I created two classes in C#, one that defines the attibute, and one that defines the generic portion:

[AttributeUsage(AttributeTargets.Class)]
public abstract class MyGenericAttribute : Attribute { }

public abstract class MyGenericAttributeMock<T>
{
  public abstract void Consume(T target);
}


Read more: jasonbock.net
QR: Default.aspx?blog=entry.b0b97ed428874abb9dcc3fbb0f9b529d

Posted via email from Jasper-net

0 comments: