Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest most elegant way to utilize a custom attribute

So a little confession, I've never written an attribute class. I understand they serve the purpose of decorating classes with flags or extra functionality possibly.

Can someone give me a quick example of not just creating and applying an attribute to a class, but rather utilizing the attribute from another block of code. The only code samples I've ever seen to utilize any form of attributes was doing so with reflection, though I've always hoped there's a way of using them without reflection.

like image 790
Jimmy Hoffa Avatar asked Jul 28 '10 20:07

Jimmy Hoffa


People also ask

What are custom attributes?

Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.

How do I add custom attributes to my framework?

AttributeUsage has a named parameter, AllowMultiple , with which you can make a custom attribute single-use or multiuse. In the following code example, a multiuse attribute is created. In the following code example, multiple attributes of the same type are applied to a class. [Author("P.

How do I create a custom attribute in .NET core?

Declaring Custom AttributesWe can define an attribute by creating a class. This class should inherit from the Attribute class. Microsoft recommends appending the 'Attribute' suffix to the end of the class's name. After that, each property of our derived class will be a parameter of the desired data type.

How can you specify target for a custom attribute?

Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.


1 Answers

Attributes are always used with reflection. They are baked into the metadata of the types during compile time and the only way to read them is through reflection. Attributes are used when you want write a type and you want to associate some metadata with it which could be used by consumers of this type.

like image 89
Darin Dimitrov Avatar answered Sep 27 '22 21:09

Darin Dimitrov