When is it run? Does it run for each object to which I apply it, or just once? Can it do anything, or its actions are restricted?
Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime. Attributes are used to impose conditions or to increase the efficiency of a piece of code.
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.
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.
Custom attributes are a lightweight way to include additional properties in a Square data model. You can use custom attributes to extend Square's data model to make it more specific to the business problem you are trying to solve.
When is the constructor run? Try it out with a sample:
class Program { static void Main(string[] args) { Console.WriteLine("Creating MyClass instance"); MyClass mc = new MyClass(); Console.WriteLine("Setting value in MyClass instance"); mc.Value = 1; Console.WriteLine("Getting attributes for MyClass type"); object[] attributes = typeof(MyClass).GetCustomAttributes(true); } } [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { public MyAttribute() { Console.WriteLine("Running constructor"); } } [MyAttribute] class MyClass { public int Value { get; set; } }
And what is the output?
Creating MyClass instance Setting value in MyClass instance Getting attributes for MyClass type Running constructor
So, the attribute constructor is run when we start to examine the attribute. Note that the attribute is fetched from the type, not the instance of the type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With