798

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?

Community
  • 1
  • 1
wusher
  • 12,291
  • 22
  • 72
  • 95
  • 30
    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. – Muthu Ganapathy Nathan May 07 '13 at 11:34

32 Answers32

685

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

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Vivek
  • 16,360
  • 5
  • 30
  • 37
  • 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 '09 at 13:24
  • 18
    Be careful with this, it bites much bigger chunk out of your CPU than ToString. – Nikola Radosavljević Nov 22 '11 at 00: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. – Øyvind Skaar Oct 25 '12 at 10:56
  • 5
    @NikolaRadosavljević would it only take up CPU power during debugging – Nickolay Kondratyev Feb 17 '13 at 06: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: http://blogs.msdn.com/b/jaredpar/archive/2011/03/18/debuggerdisplay-attribute-best-practices.aspx – Nikola Radosavljević Feb 18 '13 at 10:33
  • 1
    @Nikola: only talks about debugging performance there. – Per Lundberg Oct 07 '13 at 05:11
  • 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. – Jim Wolff Oct 08 '18 at 11:11
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.

Kols
  • 3,641
  • 2
  • 34
  • 42
Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
  • 1
    I like the Obsolete flag but it just raises a warning. Most people I have ran into ignore the warnings in VS – wusher Oct 02 '08 at 17:49
  • 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 Oct 03 '08 at 21:35
  • 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. :) – Adrian Clark Dec 01 '08 at 02:36
  • 14
    Once you clean up all the warnings, wouldn't it be better to just delete the method? – Pedro Jan 15 '09 at 23:00
  • 10
    @Pedro: Sometimes you can't for backwards compatibility reasons. If it's private and unused, yeah, delete it. – Fantius Jun 02 '09 at 16:55
  • 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 Sep 16 '09 at 13:26
  • 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? – Dan Herbert Sep 16 '09 at 13:34
  • 2
    @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 Sep 16 '09 at 13:57
  • 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... – Dan Herbert Sep 16 '09 at 14:27
  • 2
    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... http://www.codefromjames.com/wordpress/?p=131 – jocull Aug 23 '12 at 01:51
  • 1
    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. – Tarka Jun 22 '17 at 16:15
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

Kols
  • 3,641
  • 2
  • 34
  • 42
Shog9
  • 156,901
  • 35
  • 231
  • 235
  • So what exactly does the Flags attribute do? – Andrei Rînea Sep 28 '08 at 11:20
  • I think the enum needs to inherit from int does it not? – Martin Clarke Sep 28 '08 at 17:43
  • @Andrei: It turns the enumeration type into a bitfield type, with supporting metadata. – Shog9 Sep 28 '08 at 18:22
  • @Martin: int is the default type; if you wanted something else, you would specify it. – Shog9 Sep 28 '08 at 18:24
  • 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 '08 at 09: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 '08 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 '12 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 '12 at 07:33
  • @leppie 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. – Alexander May 02 '19 at 14:42
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.

Kols
  • 3,641
  • 2
  • 34
  • 42
Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
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!

Peter
  • 37,042
  • 39
  • 142
  • 198
wprl
  • 24,489
  • 11
  • 55
  • 70
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.

Kols
  • 3,641
  • 2
  • 34
  • 42
Steve Cooper
  • 20,542
  • 15
  • 71
  • 88
  • 5
    isnt this the same as doing #if DEBUG ? – Neil N Aug 10 '09 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 '11 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. – Steve Cooper Mar 15 '11 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. http://msdn.microsoft.com/en-us/library/aa664622.aspx http://blogs.msdn.com/b/jmstall/archive/2007/10/15/trivia-about-the-conditional-attribute.aspx – Mark Sowul Oct 02 '12 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.

Anthony Brien
  • 6,106
  • 7
  • 43
  • 56
  • 3
    Cant believe none pointed out `Description` until you.. Its the most helpful for me when used with enums.. – nawfal Jun 09 '13 at 08: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.

Kols
  • 3,641
  • 2
  • 34
  • 42
Gilligan
  • 1,505
  • 2
  • 15
  • 16
  • It's actually referred to a psuedoattribute, as C# emits a metadata flag for [Serializable], not a custom attribute instance ;) – TraumaPony Sep 28 '08 at 00: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 04 '09 at 19:55
  • I'll second that shoosh! – John B Apr 15 '09 at 00:17
  • System.NonSerializedAttribute is useful if you want more control over automatic serialization. – M. Jahedbozorgan Apr 29 '09 at 08: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 '10 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.

Julian
  • 33,915
  • 22
  • 119
  • 174
Chris Wenham
  • 23,679
  • 13
  • 59
  • 69
  • 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 '09 at 00: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.

Kols
  • 3,641
  • 2
  • 34
  • 42
xrost
  • 179
  • 4
  • 5
  • 7
    Don't you mean handy for hacking a unit test on something that couldn't/shouldn't be tested? – the_drow Jul 13 '11 at 05:20
  • @the_drow: You talk about 'private accessors': http://msdn.microsoft.com/en-us/library/ms184807%28v=vs.80%29.aspx – habakuk Jul 12 '12 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 '12 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 '12 at 09:16
  • @habakuk: If it should be tested, it should be public. – the_drow Jul 13 '12 at 11:10
  • 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 '12 at 14:53
44

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

Kols
  • 3,641
  • 2
  • 34
  • 42
Redwood
  • 66,744
  • 41
  • 126
  • 187
28

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

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

Kols
  • 3,641
  • 2
  • 34
  • 42
Adrian Wible
  • 1,694
  • 1
  • 13
  • 20
26
[XmlIgnore]

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

Tamas Czinege
  • 118,853
  • 40
  • 150
  • 176
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.

Julian
  • 33,915
  • 22
  • 119
  • 174
Ajaxx
  • 2,500
  • 4
  • 27
  • 38
  • and how to access then? Don't understand the point of your usage sample here. Can you explain? – Beachwalker Aug 21 '15 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 04 '16 at 10:54
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)]
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Neil
  • 7,227
  • 5
  • 42
  • 43
  • 6
    According to the docs, only used at design time (unfortunately). – Hans Kesting Sep 16 '09 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 05 '14 at 00:33
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.

Kols
  • 3,641
  • 2
  • 34
  • 42
Felix K.
  • 6,201
  • 2
  • 38
  • 71
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; }
}
Kols
  • 3,641
  • 2
  • 34
  • 42
configurator
  • 40,828
  • 14
  • 81
  • 115
  • 4
    very useful for WinForms components. use in conjunction with [Browsable(false)] – Mark Heath Nov 09 '10 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. – configurator Nov 09 '10 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).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
16

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

 [Serializable]
 [WebMethod]
FlySwat
  • 172,459
  • 74
  • 246
  • 311
  • 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 '08 at 01: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

wusher
  • 12,291
  • 22
  • 72
  • 95
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)]

Kols
  • 3,641
  • 2
  • 34
  • 42
Chris S
  • 64,770
  • 52
  • 221
  • 239
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

Kols
  • 3,641
  • 2
  • 34
  • 42
Ahmed Atia
  • 17,848
  • 25
  • 91
  • 133
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.

Brannon
  • 25,687
  • 5
  • 39
  • 44
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.

smdrager
  • 7,327
  • 6
  • 39
  • 49
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;
}
Jon Peterson
  • 723
  • 7
  • 21
  • Is STAThread used to prevent your application from accidentally spinning off another instance of itself at start up? – Luminous Sep 10 '14 at 12:51
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.

gkrogers
  • 8,126
  • 3
  • 29
  • 36
ElGringoGrande
  • 638
  • 6
  • 13
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.

Eldritch Conundrum
  • 8,452
  • 6
  • 42
  • 50
  • 2
    +1 for ThreadStatic, surprised nobody has mentioned it so far, and also for the statistical approach – staafl Sep 30 '13 at 21:42
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.

Kols
  • 3,641
  • 2
  • 34
  • 42
Kevin Driedger
  • 51,492
  • 15
  • 48
  • 55
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;
    }
}
}
Himanshu
  • 31,810
  • 31
  • 111
  • 133
Ming Yeh
  • 1
  • 1
  • 1
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() { }
}
gkrogers
  • 8,126
  • 3
  • 29
  • 36
M. Jahedbozorgan
  • 6,914
  • 2
  • 46
  • 51
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("")]
Sujit
  • 3,677
  • 9
  • 41
  • 50
2
// on configuration sections
[ConfigurationProperty] 

// in asp.net
[NotifyParentProperty(true)]
Cristian Libardo
  • 9,260
  • 3
  • 35
  • 41