What is the difference between [Something] and [SomethingAttribute]

This has probably already been asked, but hard to find.

What is the difference between [Something] and [SomethingAttribute] ?

Both of the following compilation files:

 [DefaultValue(false)] public bool Something { get; set; } 
 [DefaultValueAttribute(false)] public bool SomethingElse { get; set; } 

Are there any differences between them except their appearance? What is the general guide to using them?

+5
source share
3 answers

There is no functional difference. [Something] is just a shorthand syntax for [SomethingAttribute] .

From MSDN :

By convention, all attribute names end with an attribute. However, several languages ​​designed for the runtime, such as Visual Basic and C #, do not need to specify the fully qualified attribute name. For example, if you want to initialize System.ObsoleteAttribute, you only need to refer to it as deprecated.

+7
source

In most cases they are the same. As already mentioned, you can usually use them interchangeably, unless both DefaultValue and DefaultValueAttribute defined. You can use both of these methods without ambiguity using the identifier verbatim ( @ ).

Section 17.2 of C # LS makes this clearer:

 [AttributeUsage(AttributeTargets.All)] public class X: Attribute {} [AttributeUsage(AttributeTargets.All)] public class XAttribute: Attribute {} [X] // Error: ambiguity class Class1 {} [XAttribute] // Refers to XAttribute class Class2 {} [@X] // Refers to X class Class3 {} [@XAttribute] // Refers to XAttribute class Class4 {} 

This refers to the actual use of the attribute. Of course, if you need to use the type name, for example when using typeof or reflection, you will need to use the actual name that you gave the type.

+6
source

Both are the same in the context of an attribute declaration. The former is a shorter form of the latter. But that makes a difference within the method.

For example, if you say typeof(DefaultValue) in some method that will not compile. You will need to say typeof(DefaultValueAttribute) instead.

 private void DoSomething() { var type = typeof(DefaultValue);//Won't compile var type2 = typeof(DefaultValueAttribute);//Does compile } 
+2
source

Source: https://habr.com/ru/post/1213082/


All Articles