Simple Custom Attributes in C#

share1.pngThink of an Attribute as paint you can apply to a class that doesn’t necessarily need to know about the attribute, though it can.

Imagine we have a Alien Immigration system where space aliens are arriving. The class is decorated by a LifeDanger Attribute.

[LifeDanger(IsHuman = false)]
public class AlienImmigration
{}

The Attribute looks like this. It decides if an space alien is dangerous (Only humans are dangerous of course):

public class LifeDangerAttribute : Attribute
{
    public bool IsHuman { getset; }
    public bool IsDanger => IsHuman;
}

We can now create an Alien and see if they are dangerous:

public Test()
{
    //Create an Alien
    var bobTheAlien = new AlienImmigration();
 
    //Get the LifeDanger attribute
    System.Attribute[] attrs = 
            System.Attribute.GetCustomAttributes(bobTheAlien.GetType());
    var life = (LifeDangerAttribute) attrs
           .FirstOrDefault(x => x is LifeDangerAttribute);
 
    //Display the Danger
    Console.WriteLine("Dangerous?: " + life?.IsDanger);
}

Summary:  You can imagine creating other Immigration Types and using the same code to see if that Immigrant is dangerous. This allows users of your classes to apply meta data about the classes without having to change the class.

Advertisements