Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between [Something] and [SomethingAttribute] [duplicate]

This has probably been already asked but it's hard to search for.

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

Both of the following compile:

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

Are there any differences between these apart from their appearance? What's the general guideline on their use?

like image 920
Pokechu22 Avatar asked Feb 10 '15 19:02

Pokechu22


3 Answers

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

From MSDN:

By convention, all attribute names end with Attribute. However, several languages that target the runtime, such as Visual Basic and C#, do not require you to specify the full name of an attribute. For example, if you want to initialize System.ObsoleteAttribute, you only need to reference it as Obsolete.

like image 191
FishBasketGordo Avatar answered Sep 23 '22 18:09

FishBasketGordo


In most cases they are the same. As already said you can typically use them interchangeable except when you have both DefaultValue and DefaultValueAttribute defined. You can use both of these without ambiguity errors by using the verbatim identifier (@).

The C#LS section 17.2 makes this more clear:

[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 usage of the attribute. Of course if you require use of the type name such as when using typeof or reflection, you'll need to use the actual name you gave the type.

like image 33
Jeroen Vannevel Avatar answered Sep 20 '22 18:09

Jeroen Vannevel


Both are same in the context where attribute declaration goes. Former is shorter form of latter. But it does makes the difference inside a method.

For example if you say typeof(DefaultValue) in some method, that won't compile. You'll have to say typeof(DefaultValueAttribute) instead.

private void DoSomething()
{
    var type = typeof(DefaultValue);//Won't compile
    var type2 = typeof(DefaultValueAttribute);//Does compile
}
like image 25
Sriram Sakthivel Avatar answered Sep 24 '22 18:09

Sriram Sakthivel