views:

8554

answers:

27

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: http://stackoverflow.com/questions/20346/c-what-are-attributes

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

+15  A: 

[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.

Gilligan
One of my favorites too.
Maudite
It's actually referred to a psuedoattribute, as C# emits a metadata flag for [Serializable], not a custom attribute instance ;)
TraumaPony
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
I'll second that shoosh!
SkippyFire
System.NonSerializedAttribute is useful if you want more control over automatic serialization.
M. Jahedbozorgan
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.
locster
+60  A: 

[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

Shog9
care to provide an example?
SoloBold
P.S that's one I like a lot too.
SoloBold
Fair enough, example added.
Shog9
That's a GREAT example.. just lovin' it! :)
Anheledir
Wow, I am glad you adde the example. I like that one.
Maudite
So what exactly does the Flags attribute do?
Andrei Rinea
I think the enum needs to inherit from int does it not?
Martin Clarke
@Andrei: It turns the enumeration type into a bitfield type, with supporting metadata.
Shog9
@Martin: int is the default type; if you wanted something else, you would specify it.
Shog9
I hope you guys realize the Flags attribute does bugger all. It is not needed/used at all, except for the TypeConverter.
leppie
@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
worst sandwich ever. grosssssssss
Darren Kopp
Chris
+5  A: 

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

 [Serializable]
 [WebMethod]
FlySwat
[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
+19  A: 

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.

C. Lawrence Wenham
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!
SkippyFire
+62  A: 

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.

Dan Herbert
I like the Obsolete flag but it just raises a warning. Most people I have ran into ignore the warnings in VS
Maudite
Yeah, I've noticed that also. I've worked on applications where there are hundreds of warnings. Most of them should have been fixed but aren't for whatever reason. I never understood it...
Dan Herbert
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. :)
Aydsman
Once you clean up all the warnings, wouldn't it be better to just delete the method?
Pedro
@Pedro: Sometimes you can't for backwards compatibility reasons. If it's private and unused, yeah, delete it.
Fantius
One thing to note about Obsolete is you can always work around the compile error by accessing a method through reflection. Even with the compile error, it's best to also throw in the method if you have to keep it around.
plinth
@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?
Dan Herbert
@Dan - if you mark Obsolete *with fail with error on compile set*, then it shouldn't *ever* be called. If it's being called at run time, then someone has violated the Obsolete...
plinth
@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...
Dan Herbert
+32  A: 

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!

~ William Riley-Land

SoloBold
posted list is for .net 1.1here is the list for 3.5http://msdn.microsoft.com/en-us/library/system.attribute.aspx(You have to scroll down a little)
Keivan
Updated the link in the question. Now it is the full list for 3.5
Martinho Fernandes
Actually that links to the latest, not 3.5 specifically.
Brian Ortiz
+16  A: 

I've found [DefaultValue] to be quite useful.

Lawrence Johnston
That's certainly not the DefaultValue attribute I was thinking of. Are you sure you didn't mean this one? http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
Kyralessa
That's the one I meant, yes. Edited the url to reflect this.
Lawrence Johnston
+162  A: 
Vivek
Ha you can comment now, right :D
SoloBold
Wow, that's really good to know. I've usually accomplished the same thing by overriding ToString, but this is better.
Brian
+15  A: 

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

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

Adrian Wible
+56  A: 

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.

Blair Conrad
So many times I wish i knew about this property
Maudite
Just a shame it's broken with closures - see http://gregbeech.com/blogs/tech/archive/2008/10/17/debuggerstepthroughattribute-doesn-t-work-with-closures.aspx for more info.
Greg Beech
Also usefull for any WM_Paint Code that you know works :)
Pondidum
+2  A: 

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 the System.STAThreadAttribute System.ThreadStaticAttribute when needed.

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

ElGringoGrande
+4  A: 

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.

Brannon
+5  A: 

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).

Marc Gravell
+1: The MethodImplAttribute sounds very interesting!
rstevens
+1  A: 

In this question I asked about any attributes that can help the .Net runtime to better perform.

Lars Truijens
+3  A: 
[TypeConverter(typeof(ExpandableObjectConverter))]

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

[Obfuscation()]

I think you can guess what this is for

Chris S
+10  A: 
[XmlIgnore]

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

+1  A: 
// on configuration sections
[ConfigurationProperty] 

// in asp.net
[NotifyParentProperty(true)]
Cristian Libardo
+7  A: 

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

Maudite
+2  A: 

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

Ahmed
+1  A: 

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 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 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.

Ajaxx
+7  A: 

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; }
}
configurator
+16  A: 

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.

Anthony Brien
+2  A: 

[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() { }
}
M. Jahedbozorgan
+10  A: 

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.

+19  A: 

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.

Steve Cooper
isnt this the same as doing #if DEBUG ?
Neil N
No, it's cleverer than that. This is the mechanism used to make sure that calls to Debug.WriteLine and such are ignored at runtime. If you define a function `F` inside a `#if DEBUG` block, and `DEBUG` isn't defined, then your app will not build if any part of it calls `F`. But if you make `F` `[Conditional("DEBUG")]` then the app will compile, but calls to `F` will not be executed, and nor will the parameters to the function. See [msdn](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx) for more.
Steve Cooper
+4  A: 

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)]

Neil Whitaker
According to the docs, only used at design time (unfortunately).
Hans Kesting
+1  A: 

[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.

Kevin Driedger