800

I know that attributes are extremely useful. There are some predefined ones such as [Browsable(false)] which allows you to hide properties in the properties tab. Here is a good question explaining attributes: What are attributes in .NET?

What are the predefined attributes (and their namespace) you actually use in your projects?

1
  • 31
    What a question? , the entire page is overflowed with beautiful answers with wonderful explanations. While I am reading through this, I got experience like interviewing many experts about thier view. +100 for the question. May 7, 2013 at 11:34

32 Answers 32

686

[DebuggerDisplay] can be really helpful to quickly see customized output of a Type when you mouse over the instance of the Type during debugging. example:

[DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]
class Customer
{
    public string FirstName;
    public string LastName;
}

This is how it should look in the debugger:

alt text

Also, it is worth mentioning that [WebMethod] attribute with CacheDuration property set can avoid unnecessary execution of the web service method.

7
  • 63
    Wow, that's really good to know. I've usually accomplished the same thing by overriding ToString, but this is better.
    – Brian
    Sep 16, 2009 at 13:24
  • 18
    Be careful with this, it bites much bigger chunk out of your CPU than ToString. Nov 22, 2011 at 0:42
  • 2
    You can also use this to display the result of methods. This can make for a quite confusing debugging experience if the method (or property-get) has side effects. Oct 25, 2012 at 10:56
  • 5
    @NikolaRadosavljević would it only take up CPU power during debugging Feb 17, 2013 at 6:19
  • 2
    @Nickolay Kondratyev: I don't know all ins and outs, but you can take a look in following web service best practices which can take you to some conclusions: blogs.msdn.com/b/jaredpar/archive/2011/03/18/… Feb 18, 2013 at 10:33
274

System.Obsolete is one of the most useful attributes in the framework, in my opinion. The ability to raise a warning about code that should no longer be used is very useful. I love having a way to tell developers that something should no longer be used, as well as having a way to explain why and point to the better/new way of doing something.

The Conditional attribute is pretty handy too for debug usage. It allows you to add methods in your code for debug purposes that won't get compiled when you build your solution for release.

Then there are a lot of attributes specific to Web Controls that I find useful, but those are more specific and don't have any uses outside of the development of server controls from what I've found.

11
  • 50
    You can pass "true" as one of the parameters to System.Obsolete which causes the warning to become an error therefore breaking the build. Obviously this should be done once you have cleaned up all the warnings. :) Dec 1, 2008 at 2:36
  • 14
    Once you clean up all the warnings, wouldn't it be better to just delete the method?
    – Pedro
    Jan 15, 2009 at 23:00
  • 10
    @Pedro: Sometimes you can't for backwards compatibility reasons. If it's private and unused, yeah, delete it.
    – Fantius
    Jun 2, 2009 at 16:55
  • 3
    @plinth Throwing an exception would be a bad idea for many reasons, #1 being that the main reason to use Obsolete() is so you can keep compiled code working while in a transition phase. If you're not allowing anyone to call the method, why not just delete it? Sep 16, 2009 at 13:34
  • 17
    @plinth It's to prevent new code from using the method. Old code will remain binary compatible if a method is marked obsolete, but it will stop working if you throw an exception. If someone is using reflection to get around the "Obsolte" flag, then you have worse problems... Sep 16, 2009 at 14:27
207

[Flags] is pretty handy. Syntactic sugar to be sure, but still rather nice.

[Flags] 
enum SandwichStuff
{
   Cheese = 1,
   Pickles = 2,
   Chips = 4,
   Ham = 8,
   Eggs = 16,
   PeanutButter = 32,
   Jam = 64
};

public Sandwich MakeSandwich(SandwichStuff stuff)
{
   Console.WriteLine(stuff.ToString());
   // ...
}

// ...

MakeSandwich(SandwichStuff.Cheese 
   | SandwichStuff.Ham 
   | SandwichStuff.PeanutButter);
// produces console output: "Cheese, Ham, PeanutButter"

Leppie points out something I hadn't realized, and which rather dampens my enthusiasm for this attribute: it does not instruct the compiler to allow bit combinations as valid values for enumeration variables, the compiler allows this for enumerations regardless. My C++ background showing through... sigh

9
  • So what exactly does the Flags attribute do? Sep 28, 2008 at 11:20
  • 13
    I hope you guys realize the Flags attribute does bugger all. It is not needed/used at all, except for the TypeConverter.
    – leppie
    Oct 13, 2008 at 9:27
  • 3
    @leppie: ToString() as well. But... wow. For some reason, i had been expecting the behavior of enumerations without the attribute to be the same as C++: or'd values produce an integer (can't be passed as-is to method expecting enum param). I see now that is not the case. Weak... ok, .NET enums suck.
    – Shog9
    Oct 13, 2008 at 17:46
  • 2
    [Flags] really only helps the debugger and .ToString() functions know that a value is potentially a combination of several declarations in the enum. I'm not sure, it might make Intellisense help you use the enum more effectively too.
    – Kenzi
    Feb 18, 2012 at 16:19
  • 32
    [Flags] does have a bigger use than being just syntactic sugar. While using web services, the serialization/de-serialization won't work if a value like SandwichStuff.Cheese | SandwichStuff.Ham | SandwichStuff.Jam is passed. Without the [Flags] attribute the deserializer won't know that the value can be a combination of flags. Learnt this the hard way after spending about two days on thinking why my WCF wasn't working.
    – Anchit
    Jul 20, 2012 at 7:33
179

I like [DebuggerStepThrough] from System.Diagnostics.

It's very handy for avoiding stepping into those one-line do-nothing methods or properties (if you're forced to work in an early .Net without automatic properties). Put the attribute on a short method or the getter or setter of a property, and you'll fly right by even when hitting "step into" in the debugger.

6
  • 6
    So many times I wish i knew about this property
    – wusher
    Sep 28, 2008 at 3:23
  • 1
    Just a shame it's broken with closures - see gregbeech.com/blogs/tech/archive/2008/10/17/… for more info.
    – Greg Beech
    Dec 1, 2008 at 2:33
  • 3
    Also usefull for any WM_Paint Code that you know works :)
    – Pondidum
    May 2, 2009 at 12:56
  • @GregBeech That URL returns a .NET error. Classy! :)
    – smdrager
    Jun 8, 2012 at 12:44
  • @smdrager - Must have been a temporary issue, seems to work for me today.
    – Greg Beech
    Jun 17, 2012 at 9:37
138

For what it's worth, here's a list of all .NET attributes. There are several hundred.

I don't know about anyone else but I have some serious RTFM to do!

6
  • 34
    posted list is for .net 1.1 here is the list for 3.5 msdn.microsoft.com/en-us/library/system.attribute.aspx (You have to scroll down a little)
    – kay.one
    Jun 30, 2009 at 6:56
  • 2
    Updated the link in the question. Now it is the full list for 3.5 Nov 8, 2009 at 13:17
  • 8
    Actually that links to the latest, not 3.5 specifically. Jun 27, 2010 at 17:29
  • 1
    Now if only the list wasn't just a list of links, but the name and description. Oh well. @BrianOrtiz is right. The list is at version 4.5.
    – Luminous
    Sep 10, 2014 at 12:49
  • You just change the framework you are targeting at the top where it says "Other Versions".
    – Novaterata
    Feb 6, 2015 at 19:01
132

My vote would be for Conditional

[Conditional("DEBUG")]
public void DebugOnlyFunction()
{
    // your code here
}

You can use this to add a function with advanced debugging features; like Debug.Write, it is only called in debug builds, and so allows you to encapsulate complex debug logic outside the main flow of your program.

4
  • 5
    isnt this the same as doing #if DEBUG ?
    – Neil N
    Aug 10, 2009 at 20:11
  • 10
    Somewhat, #if DEBUG means that the caller has to also not call it, while the Conditioinal leaves the call but makes it a NOP that gets eliminated at JIT.
    – Rangoric
    Mar 14, 2011 at 20:10
  • 23
    Also, you would typically use #if DEBUG around calls, and [Conditional] around methods. So if you call a debugging method 100 times, turning it off is a matter of a single code change, not 100. Mar 15, 2011 at 11:46
  • 14
    Rangoric's comment is subtly wrong (at least for C#): the method is included unmodified; the call site itself is omitted. This has a few implications: parameters are not evaluated, and the conditional method is contained, unmodified, in the compiler's output. You can verify this with reflection. msdn.microsoft.com/en-us/library/aa664622.aspx blogs.msdn.com/b/jmstall/archive/2007/10/15/…
    – Mark Sowul
    Oct 2, 2012 at 20:06
98

I always use the DisplayName, Description and DefaultValue attributes over public properties of my user controls, custom controls or any class I'll edit through a property grid. These tags are used by the .NET PropertyGrid to format the name, the description panel, and bolds values that are not set to the default values.

[DisplayName("Error color")]
[Description("The color used on nodes containing errors.")]
[DefaultValue(Color.Red)]
public Color ErrorColor
{
    ...
} 

I just wish Visual Studio's IntelliSense would take the Description attribute into account if no XML comment are found. It would avoid having to repeat the same sentence twice.

1
  • 3
    Cant believe none pointed out Description until you.. Its the most helpful for me when used with enums..
    – nawfal
    Jun 9, 2013 at 8:05
69

[Serializable] is used all the time for serializing and deserializing objects to and from external data sources such as xml or from a remote server. More about it here.

5
  • It's actually referred to a psuedoattribute, as C# emits a metadata flag for [Serializable], not a custom attribute instance ;)
    – TraumaPony
    Sep 28, 2008 at 0:50
  • 1
    While very useful [Serializable] is far from perfect. It requires way too much tinkering and trial and error to get the result you want.
    – shoosh
    Jan 4, 2009 at 19:55
  • I'll second that shoosh!
    – John B
    Apr 15, 2009 at 0:17
  • System.NonSerializedAttribute is useful if you want more control over automatic serialization. Apr 29, 2009 at 8:51
  • As a side note I would add that the performance of the built-in .Net serialization is pretty poor, like 2 or 3 orders of magnitude slower than hand crafted code.
    – redcalx
    Jan 13, 2010 at 11:52
57

In Hofstadtian spirit, the [Attribute] attribute is very useful, since it's how you create your own attributes. I've used attributes instead of interfaces to implement plugin systems, add descriptions to Enums, simulate multiple dispatch and other tricks.

1
  • 14
    Sounds cool! Would you mind showing some examples of the plugin system and the enum descriptions? Those are both things I'm interested in implementing myself!
    – John B
    Apr 15, 2009 at 0:17
46

Here is the post about interesting attribute InternalsVisibleTo. Basically what it does it mimics C++ friends access functionality. It comes very handy for unit testing.

6
  • 7
    Don't you mean handy for hacking a unit test on something that couldn't/shouldn't be tested?
    – the_drow
    Jul 13, 2011 at 5:20
  • @the_drow: You talk about 'private accessors': msdn.microsoft.com/en-us/library/ms184807%28v=vs.80%29.aspx
    – habakuk
    Jul 12, 2012 at 12:18
  • @habakuk: Not really. There are cases where internal classes should be exposed for unit testing, usually due to bad design.
    – the_drow
    Jul 12, 2012 at 15:27
  • 2
    @the_drow: I wouldn't say that InternalsVisibleTo is evil for unit testing; you can create and test smaller "units" that are not visible outside your project (it helps you to have a clean and small api). But if you need 'private accessors' to unit test something there is probably something wrong.
    – habakuk
    Jul 13, 2012 at 9:16
  • 10
    @the_drow I disagree with your assertion that internal isn't public. It's public within the assembly that is being tested and should be unit tested so that other classes within the assembly can assume it's correction functionality. If you don't unit test it, you'll have to test its functions in all of the consuming classes.
    – tvanfosson
    Dec 10, 2012 at 14:53
28

I'd suggest [TestFixture] and [Test] - from the nUnit library.

Unit tests in your code provide safety in refactoring and codified documentation.

26
[XmlIgnore]

as this allows you to ignore (in any xml serialisation) 'parent' objects that would otherwise cause exceptions when saving.

25

It's not well-named, not well-supported in the framework, and shouldn't require a parameter, but this attribute is a useful marker for immutable classes:

[ImmutableObject(true)]
2
  • 6
    According to the docs, only used at design time (unfortunately). Sep 16, 2009 at 13:35
  • 1
    Given that this is design-time only, perhaps it would be better to create your own ImmutableObjectAttribute class -- at least you could eliminate the parameter.
    – Roy Tinker
    Mar 5, 2014 at 0:33
25

I like using the [ThreadStatic] attribute in combination with thread and stack based programming. For example, if I want a value that I want to share with the rest of a call sequence, but I want to do it out of band (i.e. outside of the call parameters), I might employ something like this.

class MyContextInformation : IDisposable {
    [ThreadStatic] private static MyContextInformation current;

    public static MyContextInformation Current {
        get { return current; }
    }

    private MyContextInformation previous;


    public MyContextInformation(Object myData) {
       this.myData = myData;
       previous = current;
       current = this;
    }

    public void Dispose() {
       current = previous;
    }
}

Later in my code, I can use this to provide contextual information out of band to people downstream from my code. Example:

using(new MyContextInformation(someInfoInContext)) {
   ...
}

The ThreadStatic attribute allows me to scope the call only to the thread in question avoiding the messy problem of data access across threads.

2
  • and how to access then? Don't understand the point of your usage sample here. Can you explain? Aug 21, 2015 at 11:00
  • @Beachwalker Current should be static, edited it now. Now you can access MyContextInformation.Current to get the active context on the stack. This is something which is a very good concept in certain cases, our ( my companys ) engine uses it for a lot of purposes.
    – Felix K.
    Jan 4, 2016 at 10:54
23

The DebuggerHiddenAttribute which allows to avoiding step into code which should not be debugged.

public static class CustomDebug
{
    [DebuggerHidden]
    public static void Assert(Boolean condition, Func<Exception> exceptionCreator) { ... }
}

...

// The following assert fails, and because of the attribute the exception is shown at this line
// Isn't affecting the stack trace
CustomDebug.Assert(false, () => new Exception()); 

Also it prevents from showing methods in stack trace, useful when having a method which just wraps another method:

[DebuggerHidden]
public Element GetElementAt(Vector2 position)
{
    return GetElementAt(position.X, position.Y);
}

public Element GetElementAt(Single x, Single y) { ... }

If you now call GetElementAt(new Vector2(10, 10)) and a error occurs at the wrapped method, the call stack is not showing the method which is calling the method which throws the error.

21

DesignerSerializationVisibilityAttribute is very useful. When you put a runtime property on a control or component, and you don't want the designer to serialize it, you use it like this:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Foo Bar {
    get { return baz; }
    set { baz = value; }
}
2
  • 4
    very useful for WinForms components. use in conjunction with [Browsable(false)]
    – Mark Heath
    Nov 9, 2010 at 17:21
  • 4
    Good point - [Browsable(false)] is required to hide it from the designer's user, where [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] is required so it won't get serialized. Nov 9, 2010 at 17:46
17

Only a few attributes get compiler support, but one very interesting use of attributes is in AOP: PostSharp uses your bespoke attributes to inject IL into methods, allowing all manner of abilities... log/trace being trivial examples - but some other good examples are things like automatic INotifyPropertyChanged implementation (here).

Some that occur and impact the compiler or runtime directly:

  • [Conditional("FOO")] - calls to this method (including argument evaluation) only occur if the "FOO" symbol is defined during build
  • [MethodImpl(...)] - used to indicate a few thing like synchronization, inlining
  • [PrincipalPermission(...)] - used to inject security checks into the code automatically
  • [TypeForwardedTo(...)] - used to move types between assemblies without rebuilding the callers

For things that are checked manually via reflection - I'm a big fan of the System.ComponentModel attributes; things like [TypeDescriptionProvider(...)], [TypeConverter(...)], and [Editor(...)] which can completely change the behavior of types in data-binding scenarios (i.e. dynamic properties etc).

0
16

If I were to do a code coverage crawl, I think these two would be top:

 [Serializable]
 [WebMethod]
1
  • 16
    [WebMethod] is used to decorate a method that is exposed in a web service. [Serializable] marks your objects such that they can be serialized for purposes such as passing them across app domains.
    – Kev
    Sep 28, 2008 at 1:28
15

I have been using the [DataObjectMethod] lately. It describes the method so you can use your class with the ObjectDataSource ( or other controls).

[DataObjectMethod(DataObjectMethodType.Select)] 
[DataObjectMethod(DataObjectMethodType.Delete)] 
[DataObjectMethod(DataObjectMethodType.Update)] 
[DataObjectMethod(DataObjectMethodType.Insert)] 

More info

0
12

In our current project, we use

[ComVisible(false)]

It controls accessibility of an individual managed type or member, or of all types within an assembly, to COM.

More Info

12
[TypeConverter(typeof(ExpandableObjectConverter))]

Tells the designer to expand the properties which are classes (of your control)

[Obfuscation]

Instructs obfuscation tools to take the specified actions for an assembly, type, or member. (Although typically you use an Assembly level [assembly:ObfuscateAssemblyAttribute(true)]

4
  • 1
    I did guess, but was wrong. The Obfuscation attribute is only a hint for 3rd party obfsucators. It doesn't cause the compiler to obfuscate anything by default. Jan 4, 2012 at 14:25
  • @DanNeely free for Visual Studio Pro/Ultimate users!
    – Chris S
    Jan 4, 2012 at 15:23
  • 4
    If you're referring to DotFuscator Community Edition, the level of protection is provides is so low that at best it barely counts for anything. Jan 4, 2012 at 15:39
  • @ricovox I've added a summary
    – Chris S
    Jan 3, 2013 at 14:54
9

The attributes I use the most are the ones related to XML Serialization.

XmlRoot

XmlElement

XmlAttribute

etc...

Extremely useful when doing any quick and dirty XML parsing or serializing.

8

Being a middle tier developer I like

System.ComponentModel.EditorBrowsableAttribute Allows me to hide properties so that the UI developer is not overwhelmed with properties that they don't need to see.

System.ComponentModel.BindableAttribute Some things don't need to be databound. Again, lessens the work the UI developers need to do.

I also like the DefaultValue that Lawrence Johnston mentioned.

System.ComponentModel.BrowsableAttribute and the Flags are used regularly.

I use System.STAThreadAttribute System.ThreadStaticAttribute when needed.

By the way. I these are just as valuable for all the .Net framework developers.

8

[EditorBrowsable(EditorBrowsableState.Never)] allows you to hide properties and methods from IntelliSense if the project is not in your solution. Very helpful for hiding invalid flows for fluent interfaces. How often do you want to GetHashCode() or Equals()?

For MVC [ActionName("Name")] allows you to have a Get action and Post action with the same method signature, or to use dashes in the action name, which otherwise would not be possible without creating a route for it.

8

I consider that is important to mention here that the following attributes are also very important:

STAThreadAttribute 

Indicates that the COM threading model for an application is single-threaded apartment (STA).

For example this attribute is used in Windows Forms Applications:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

And also ...

SuppressMessageAttribute

Suppresses reporting of a specific static analysis tool rule violation, allowing multiple suppressions on a single code artifact.

For example:

[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isChecked")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "fileIdentifier")]
static void FileNode(string name, bool isChecked)
{
    string fileIdentifier = name;
    string fileName = name;
    string version = String.Empty;
}
1
  • Is STAThread used to prevent your application from accidentally spinning off another instance of itself at start up?
    – Luminous
    Sep 10, 2014 at 12:51
7

Off the top of my head, here is a quick list, roughly sorted by frequency of use, of predefined attributes I actually use in a big project (~500k LoCs):

Flags, Serializable, WebMethod, COMVisible, TypeConverter, Conditional, ThreadStatic, Obsolete, InternalsVisibleTo, DebuggerStepThrough.

1
  • 2
    +1 for ThreadStatic, surprised nobody has mentioned it so far, and also for the statistical approach
    – staafl
    Sep 30, 2013 at 21:42
6

I generates data entity class via CodeSmith and I use attributes for some validation routine. Here is an example:

/// <summary>
/// Firm ID
/// </summary>
[ChineseDescription("送样单位编号")]
[ValidRequired()]
public string FirmGUID
{
    get { return _firmGUID; }
    set { _firmGUID = value; }
}

And I got an utility class to do the validation based on the attributes attached to the data entity class. Here is the code:

namespace Reform.Water.Business.Common
{
/// <summary>
/// Validation Utility
/// </summary>
public static class ValidationUtility
{
    /// <summary>
    /// Data entity validation
    /// </summary>
    /// <param name="data">Data entity object</param>
    /// <returns>return true if the object is valid, otherwise return false</returns>
    public static bool Validate(object data)
    {
        bool result = true;
        PropertyInfo[] properties = data.GetType().GetProperties();
        foreach (PropertyInfo p in properties)
        {
            //Length validatioin
            Attribute attribute = Attribute.GetCustomAttribute(p,typeof(ValidLengthAttribute), false);
            if (attribute != null)
            {
                ValidLengthAttribute validLengthAttribute = attribute as ValidLengthAttribute;
                if (validLengthAttribute != null)
                {
                    int maxLength = validLengthAttribute.MaxLength;
                    int minLength = validLengthAttribute.MinLength;
                    string stringValue = p.GetValue(data, null).ToString();
                    if (stringValue.Length < minLength || stringValue.Length > maxLength)
                    {
                        return false;
                    }
                }
            }
            //Range validation
            attribute = Attribute.GetCustomAttribute(p,typeof(ValidRangeAttribute), false);
            if (attribute != null)
            {
                ValidRangeAttribute validRangeAttribute = attribute as ValidRangeAttribute;
                if (validRangeAttribute != null)
                {
                    decimal maxValue = decimal.MaxValue;
                    decimal minValue = decimal.MinValue;
                    decimal.TryParse(validRangeAttribute.MaxValueString, out maxValue);
                    decimal.TryParse(validRangeAttribute.MinValueString, out minValue);
                    decimal decimalValue = 0;
                    decimal.TryParse(p.GetValue(data, null).ToString(), out decimalValue);
                    if (decimalValue < minValue || decimalValue > maxValue)
                    {
                        return false;
                    }
                }
            }
            //Regex validation
            attribute = Attribute.GetCustomAttribute(p,typeof(ValidRegExAttribute), false);
            if (attribute != null)
            {
                ValidRegExAttribute validRegExAttribute = attribute as ValidRegExAttribute;
                if (validRegExAttribute != null)
                {
                    string objectStringValue = p.GetValue(data, null).ToString();
                    string regExString = validRegExAttribute.RegExString;
                    Regex regEx = new Regex(regExString);
                    if (regEx.Match(objectStringValue) == null)
                    {
                        return false;
                    }
                }
            }
            //Required field validation
            attribute = Attribute.GetCustomAttribute(p,typeof(ValidRequiredAttribute), false);
            if (attribute != null)
            {
                ValidRequiredAttribute validRequiredAttribute = attribute as ValidRequiredAttribute;
                if (validRequiredAttribute != null)
                {
                    object requiredPropertyValue = p.GetValue(data, null);
                    if (requiredPropertyValue == null || string.IsNullOrEmpty(requiredPropertyValue.ToString()))
                    {
                        return false;
                    }
                }
            }
        }
        return result;
    }
}
}
6

[DeploymentItem("myFile1.txt")] MSDN Doc on DeploymentItem

This is really useful if you are testing against a file or using the file as input to your test.

5

[System.Security.Permissions.PermissionSetAttribute] allows security actions for a PermissionSet to be applied to code using declarative security.

// usage:
public class FullConditionUITypeEditor : UITypeEditor
{
    // The immediate caller is required to have been granted the FullTrust permission.
    [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
    public FullConditionUITypeEditor() { }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.