Why can't you create a Generic type that inherits from Attribute?

  • Thread starter Thread starter Wes
  • Start date Start date
Wes,

Consider the following:

public class MyAttribute<T> : Attribute
{
}

[MyAttribute<MyClass>]
public MyClass
{
}

The compiler wouldn't know what to do, as it would have to have a type
definition for MyClass to create the metadata for MyClass, but the MyClass
type definition isn't complete without MyAttribute<T> being resolved.

You could use a compiler check to make sure that this case wasn't
applied, but I think it is a good idea that they didn't allow this for now.

Hope this helps.
 
Hello Nicholas Paldino [.NET/C# MVP],

Thanks for the response.

How is your example different from this (which is allowed):

public class MyClass
{
public List<MyClass> Get() { };
}

Thanks,
Wes Haggard
http://weblogs.asp.net/whaggard/

Wes,

Consider the following:

public class MyAttribute<T> : Attribute
{
}
[MyAttribute<MyClass>]
public MyClass
{
}
The compiler wouldn't know what to do, as it would have to have a
type definition for MyClass to create the metadata for MyClass, but
the MyClass type definition isn't complete without MyAttribute<T>
being resolved.

You could use a compiler check to make sure that this case wasn't
applied, but I think it is a good idea that they didn't allow this for
now.

Hope this helps.

Why can't you create a Generic type that inherits from Attribute? Of
course I'm talking about in C# 2.0 and .Net Framework 2.0.

I posted this question on my weblog
(http://weblogs.asp.net/whaggard/archive/2004/10/12/241476.aspx) last
week but I no one gave an answer. So I figured I would post it to
the C# newsgroup to see if anyone can shine some light on this
question for me.

Thanks
Wes Haggard
http://weblogs.asp.net/whaggard/
 
Wes said:
Why can't you create a Generic type that inherits from Attribute? Of
course I'm talking about in C# 2.0 and .Net Framework 2.0.

I posted this question on my weblog
(http://weblogs.asp.net/whaggard/archive/2004/10/12/241476.aspx) last week
but I no one gave an answer. So I figured I would post it to the C#
newsgroup to see if anyone can shine some light on this question for me.

My hypothesis would be because Attributes are serialized into metadata that
must be serializable without initalizing any data(parameters are serialized
into the containing type), however that is certainly not much of an answer.

I did a little research but I can't find any documents that may help. I
don't think you are going to find a terribly concrete answer for a while
yet.

I can say that ILASM doesn't appear to allow you to create generic
attributes in IL either, but then I just may be screwing up the IL.
 
Back
Top