Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a custom attribute's constructor run?

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?

like image 628
devoured elysium Avatar asked Jul 22 '09 22:07

devoured elysium


People also ask

What is the use of custom attributes in C#?

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.

How do you write a custom attribute?

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

What are custom attributes in square?

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.


1 Answers

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.

like image 152
Fredrik Mörk Avatar answered Sep 18 '22 16:09

Fredrik Mörk