Most Useful Attributes [closed]
Asked Answered
O

32

804

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?

Oven answered 28/9, 2008 at 0:16 Comment(1)
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.Lockhart
B
687

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

Bitch answered 28/9, 2008 at 0:16 Comment(7)
Wow, that's really good to know. I've usually accomplished the same thing by overriding ToString, but this is better.Claustrophobia
Be careful with this, it bites much bigger chunk out of your CPU than ToString.Divided
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.Medarda
@NikolaRadosavljević would it only take up CPU power during debuggingExpatriate
@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/…Divided
@Nikola: only talks about debugging performance there.Woodworker
Every time you have a curly, the inside is evaluated, which is what costs CPU, 2x curly equals 2x eval calls, so an excessive amount of calls can cost a lot of CPU (fx. showing a long list of items). a workaround to this is calling {DebuggerDisplay()} that is only one expensive call, and you can make that method return all the property names you want. Also if the method is private, it technically isn't used anywhere and will be removed during Release builds. but the Debugger can still use it during debug.Fresno
W
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.

Westhead answered 28/9, 2008 at 0:16 Comment(11)
I like the Obsolete flag but it just raises a warning. Most people I have ran into ignore the warnings in VSOven
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...Westhead
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. :)Sungod
Once you clean up all the warnings, wouldn't it be better to just delete the method?Headfirst
@Pedro: Sometimes you can't for backwards compatibility reasons. If it's private and unused, yeah, delete it.Radish
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.Elianaelianora
@Elianaelianora 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?Westhead
@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...Elianaelianora
@Elianaelianora 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...Westhead
I wrote an article around using conditional attributes for debugging awhile ago. I actually like using them better than breakpoints for certain cases. Some examples here... codefromjames.com/wordpress/?p=131Tibbetts
If you're releasing your DLLs as a versioned API you might keep the obsolete-error method around so people can get information on why it no longer works, rather than the method just not existing. [Obsolete( "Use X instead", true )] provides a reason the code doesn't compile, and offers an alternative.Rubi
S
208

[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

Sportive answered 28/9, 2008 at 0:16 Comment(9)
So what exactly does the Flags attribute do?Trisoctahedron
I think the enum needs to inherit from int does it not?Photoplay
@Andrei: It turns the enumeration type into a bitfield type, with supporting metadata.Sportive
@Martin: int is the default type; if you wanted something else, you would specify it.Sportive
I hope you guys realize the Flags attribute does bugger all. It is not needed/used at all, except for the TypeConverter.Amboceptor
@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.Sportive
[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.League
[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.Abstain
@Amboceptor the flags attribute should still be used to indicate that you can use bitwise OR. Using it on enums that are not marked with it are probably not going to be in powers of 2, making a mess.Agriculturist
O
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.

Outgoing answered 28/9, 2008 at 0:16 Comment(6)
So many times I wish i knew about this propertyOven
Just a shame it's broken with closures - see gregbeech.com/blogs/tech/archive/2008/10/17/… for more info.Synergetic
Also usefull for any WM_Paint Code that you know works :)Chiropodist
@GregBeech That URL returns a .NET error. Classy! :)Lamb
@Lamb - Must have been a temporary issue, seems to work for me today.Synergetic
[DebuggerHidden] is another good one. It forces thrown errors to break in the calling method (for stuff like DB handlers)Adversary
A
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!

Asylum answered 28/9, 2008 at 0:16 Comment(6)
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)Cartilage
Updated the link in the question. Now it is the full list for 3.5Alwitt
Actually that links to the latest, not 3.5 specifically.Borzoi
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.Moriah
You just change the framework you are targeting at the top where it says "Other Versions".Pescara
msdn.microsoft.com/en-us/library/… for a much larger and more recent list.Visitation
P
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.

Percival answered 28/9, 2008 at 0:16 Comment(4)
isnt this the same as doing #if DEBUG ?Trip
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.Lifeguard
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.Percival
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/…Respondent
H
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.

Hertha answered 28/9, 2008 at 0:16 Comment(1)
Cant believe none pointed out Description until you.. Its the most helpful for me when used with enums..Malliemallin
H
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.

Housing answered 28/9, 2008 at 0:16 Comment(5)
It's actually referred to a psuedoattribute, as C# emits a metadata flag for [Serializable], not a custom attribute instance ;)Hamforrd
While very useful [Serializable] is far from perfect. It requires way too much tinkering and trial and error to get the result you want.Luganda
I'll second that shoosh!Deluca
System.NonSerializedAttribute is useful if you want more control over automatic serialization.Magdaleno
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.Cadman
S
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.

Senility answered 28/9, 2008 at 0:16 Comment(1)
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!Deluca
B
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.

Beverie answered 28/9, 2008 at 0:16 Comment(6)
Don't you mean handy for hacking a unit test on something that couldn't/shouldn't be tested?Carte
@the_drow: You talk about 'private accessors': msdn.microsoft.com/en-us/library/ms184807%28v=vs.80%29.aspxRealm
@habakuk: Not really. There are cases where internal classes should be exposed for unit testing, usually due to bad design.Carte
@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.Realm
@habakuk: If it should be tested, it should be public.Carte
@Carte 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.Tracheotomy
W
44

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

Westhead answered 28/9, 2008 at 0:16 Comment(0)
V
28

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

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

Veta answered 28/9, 2008 at 0:16 Comment(0)
C
26
[XmlIgnore]

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

Clangor answered 28/9, 2008 at 0:16 Comment(0)
W
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)]
Wilma answered 28/9, 2008 at 0:16 Comment(2)
According to the docs, only used at design time (unfortunately).Kayo
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.Amylene
S
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.

Sulfanilamide answered 28/9, 2008 at 0:16 Comment(2)
and how to access then? Don't understand the point of your usage sample here. Can you explain?Dishonor
@Dishonor 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.Faltboat
F
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.

Faltboat answered 28/9, 2008 at 0:16 Comment(0)
S
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; }
}
Stay answered 28/9, 2008 at 0:16 Comment(2)
very useful for WinForms components. use in conjunction with [Browsable(false)]Lemons
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.Stay
B
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).

Brunet answered 28/9, 2008 at 0:16 Comment(0)
L
16

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

 [Serializable]
 [WebMethod]
Lukin answered 28/9, 2008 at 0:16 Comment(1)
[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.Significant
O
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

Oven answered 28/9, 2008 at 0:16 Comment(0)
C
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

Coumas answered 28/9, 2008 at 0:16 Comment(0)
F
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)]

Fantastic answered 28/9, 2008 at 0:16 Comment(4)
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.Subjectivism
@DanNeely free for Visual Studio Pro/Ultimate users!Fantastic
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.Subjectivism
@ricovox I've added a summaryFantastic
S
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.

Stephi answered 28/9, 2008 at 0:16 Comment(0)
R
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;
}
Radiomicrometer answered 28/9, 2008 at 0:16 Comment(1)
Is STAThread used to prevent your application from accidentally spinning off another instance of itself at start up?Moriah
L
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.

Lamb answered 28/9, 2008 at 0:16 Comment(0)
S
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.

Sedda answered 28/9, 2008 at 0:16 Comment(0)
R
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.

Razee answered 28/9, 2008 at 0:16 Comment(1)
+1 for ThreadStatic, surprised nobody has mentioned it so far, and also for the statistical approachIndian
K
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;
    }
}
}
Knives answered 28/9, 2008 at 0:16 Comment(0)
E
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.

Essary answered 28/9, 2008 at 0:16 Comment(0)
M
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() { }
}
Missi answered 28/9, 2008 at 0:16 Comment(0)
F
2

I always use attributes, [Serializable], [WebMethod], [DefaultValue], [Description("description here")].

but beside that there is a Global Attributes in c#.

[assembly: System.CLSCompliant(true)]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]
Fleecy answered 28/9, 2008 at 0:16 Comment(0)
S
2
// on configuration sections
[ConfigurationProperty] 

// in asp.net
[NotifyParentProperty(true)]
Sirrah answered 28/9, 2008 at 0:16 Comment(1)
what is the purpose of NotifyParentProperty?Dric

© 2022 - 2024 — McMap. All rights reserved.