-4

Syntactically I understand how C# attributes are applied (i.e. denoted in square brackets []). But it is not obvious what effects adding attributes actually has.

For instance:

  • Are attributes meant to be a type of commenting?
  • How are these attributes handled by the C# compiler?
  • Will these C# attributes change the C# program execution in any way?
StayOnTarget
  • 9,925
  • 10
  • 45
  • 68
Explorer
  • 195
  • 10
  • 1
    No these are not used for comments. Usually these are used to annotate methodes, classes, etc. To perform analysis and automate tasks, like reflection. – Willem Van Onsem Aug 08 '17 at 23:45
  • Possible duplicate of [Attributes in C#](https://stackoverflow.com/questions/726029/attributes-in-c-sharp) – StayOnTarget May 09 '18 at 18:37

2 Answers2

4

Attributes are not comments; they are classes that get added to the metadata of "things" in C#. By "things" I mean classes, properties, methods, etc.

An attribute absolutely can change the execution of a program... if something uses Reflection to read and act on the attributes. For example; the [DataMember] attribute will allow a DataContractSerializer to include that member in a serialized object. The [Export] attribute will be picked up by MEF code as a plugin.

There are many other examples and you can also create your own. For far more information about attributes see: Attributes in C#

BradleyDotNET
  • 59,038
  • 10
  • 94
  • 113
0

Attributes are a powerful construct that can indirectly affect the code execution. You can inspect self or other classes using Reflection and change behaviour based on the presence of certain attributes.

Take a look at the c# programming guide: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/

Z.D.
  • 12,393
  • 1
  • 32
  • 54