Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use 'custom attributes' in your code (.NET)

Could anyone explain the benefits (or reasons) to use custom attributes in your code. Of course I use (and understand the purpose of) defined attributes in certain scenarios (WCF, Serialization etc.), but I cannot imagine any algorithms where I would need to create and use my own custom attributes. Could someone provide a real-world case where usages of custom defined attributes bring something to a project.

like image 341
Slava Kovalchuk Avatar asked Oct 24 '11 15:10

Slava Kovalchuk


People also ask

Why do we need custom attributes in C#?

Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime.

What are custom attributes used for?

Custom attributes are attributes that are not part of the standard HTML5 attributes but are explicitly created. They allow us to add our own information to HTML tags. These are not specific and can be used with all the HTML elements.

What is custom attribute in C#?

Creating Custom Attributes (C#) The class name AuthorAttribute is the attribute's name, Author , plus the Attribute suffix. It is derived from System. Attribute , so it is a custom attribute class. The constructor's parameters are the custom attribute's positional parameters.

What are attributes in dot net?

Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The . Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.


2 Answers

The same reason as for WCF etc, but something that's specific to your project - you want to add some metadata to some members (types, fields, methods, whatever) to specify something about the mechanism involved, and it's not something which is covered by existing attributes.

For example, NUnit wanted to add their own indication that a particular type contained unit tests - there was no such existing attribute, so they created TestFixtureAttribute.

It's a relatively rare event, sure - but it can happen.

like image 183
Jon Skeet Avatar answered Sep 30 '22 21:09

Jon Skeet


If you want to write your own system like WCF, Serialization, etc...

If you write code that iterates over types or members and does things with them, you will frequently want to use your own custom attributes to mark some members as being different or special.

like image 32
SLaks Avatar answered Sep 30 '22 21:09

SLaks