Annotations in C#
Annotation is a feature present in C# and other languages for a long time, I've learned how to use some of them and what they do, but never actually dived in to understand how they work, so that's the goal here.
In the C# ecosystem, Annotations are actually called Attributes. I'll call them Attributes from now on.
They can appear in almost any piece of code, such as methods and method's parameters (HttpGet and FromQuery in the example)
```csharp filename="CommunityController.cs"
[HttpGet]
public IActionResult Index([FromQuery] int id)
{
return View(id);
}
```
Or a class' property
```csharp filename="CommunityRequest.cs"
public class CommunityRequest
{
[Display(Name = "Community Name")]
public string Name { get; set; }
}
```
It looks like a lot of engineering to implement such feature that can be used in so many places and with so many behaviours, but in reality, Attributes simply makes the C# compiler add metadata in the assembly, and that's basically it. Now, how the behaviour is implemented, it's up to the library, framework or package that is using it.
In fact, we can create our own custom Attribute and use it with object.GetType().GetProperties().GetCustomAttribute<>():
```csharp
[AttributeUsage(AttributeTargets.Property)]
public class TransformToUpperAttribute : Attribute
{
public string Transform(string valor)
{
return valor.ToUpperInvariant();
}
}
public class User
{
[TransformToUpper]
public string Name { get; set; }
}
var user = new User()
{
Name = "Example"
};
var props = user.GetType().GetProperties();
foreach (var prop in props)
{
var attribute = prop.GetCustomAttribute<TransformToUpper>();
var val = prop.GetValue(user) as string;
var result = attribute.Transform(val);
prop.SetValue(user, result);
Console.WriteLine(user.Name); // output: EXAMPLE
}
```