Home > Backend Development > C++ > Why Can't C# Have Generic Attributes?

Why Can't C# Have Generic Attributes?

Patricia Arquette
Release: 2025-01-18 22:42:12
Original
378 people have browsed it

Why Can't C# Have Generic Attributes?

Understanding C#'s Limitation on Generic Attributes

C# prohibits the use of generic types as attributes. For example, the following code:

<code class="language-csharp">public sealed class ValidatesAttribute<T> : Attribute
{

}

[Validates<string>]
public static class StringValidation
{

}</code>
Copy after login

will fail to compile. While this restriction is well-known, the reasoning behind it is less clear.

The Common Language Infrastructure (CLI) specification doesn't explicitly forbid generic attributes. However, the C# 3 specification (section 10.1.4) clearly states the prohibition without justification. The ECMA C# 2 specification offers no further clarification.

Research indicates that the decision wasn't based on technical constraints, but rather a design choice. According to Eric Lippert (summarized), the complexity added by supporting generic attributes would outweigh the benefits, leading to a more complex language and compiler without providing substantial value to developers.

The above is the detailed content of Why Can't C# Have Generic Attributes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template