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

3

5

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?

Regiment answered 10/2, 2015 at 19:59 Comment(3)
No difference; prefer [DefaultValue(false)].Neall
The better question is why does the "xxxAttribute" exist at all :-).Kernite
I suppose it would matter for DefaultValue or DefaultValueAttributeAttribute types ..Sudiesudnor
C
7

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.

Compare answered 10/2, 2015 at 20:1 Comment(0)
B
6

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.

Bobinette answered 10/2, 2015 at 20:9 Comment(0)
B
2

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
}
Bally answered 10/2, 2015 at 20:4 Comment(3)
It would be better if the downvoter can point what's wrong with the answer.Bally
There was nothing wrong. I think the down voter did not know what you're talking about since its clearly a good answerCaughey
+1 You make a good point. Outside of the declarative attribute context, you cannot just drop "Attribute" from the end.Compare

© 2022 - 2024 — McMap. All rights reserved.