Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# allow generic types to be used as attributes inside the generic class? [duplicate]

This isn't a very important question, I'm only curious why it's not allowed. The error message is not helpful in explaining, because obviously 'Att' does inherit from Attribute.

public class Generic<Att> where Att : System.Attribute
{
    [Att] //Error: 'Att' is not an attribute class
    public float number;
}
like image 209
user7486517 Avatar asked Jan 09 '19 11:01

user7486517


People also ask

Why there is no string in C?

Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable. A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0' ).

Why C has no exception handling?

As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.

What does C++ have that C doesnt?

C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language.

Why is C not outdated?

The C programming language doesn't seem to have an expiration date. It's closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software.


1 Answers

Attribute must be defined at compile time only because it's stored in dll or exe. And can contain only compile time created informaion. So, it can not be generic by this reason.

Compiler often uses attribute type or it's value, so you can't define it later.

In you example you want to mark field with generic parameter:

public class Generic<Att> where Att : System.Attribute
{
    [Att] //Error: 'Att' is not an attribute class
    public float number;
}

But it's equal to:

public class Generic<Att> where Att : System.Attribute
{
    [Attribute]
    public float number;
}

Because Att can not be replaced in future. So, no reason to use generics for attributes.

like image 190
Backs Avatar answered Oct 19 '22 17:10

Backs