C# Refresh

Nonsultant
1,499 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Attributes in C#

Attributes gives us the ability to associating metadata, or declarative information, with code (assemblies, types, methods, properties etc.). This is in C# done using [* and *], if you would like to add an attribute to a property:

[Description("This is a description of my property")]
public string MyProperty { get; set;}

Using reflection is it possible to retrieve the attributes. We are especially going to use this when working with Object-relational mapping (ORM) later in the course.

Example of reading an attribute using reflection:

using System;
using System.Reflection;
using System.ComponentModel;
public class Program{
static void Main()
{
var propertyInfo = typeof(Test).GetProperty("MyProperty");
var testDescriptionAttribute = (DescriptionAttribute)propertyInfo.GetCustomAttribute(typeof(DescriptionAttribute));
Console.WriteLine(testDescriptionAttribute.Description);
}
}
public class Test
{
[Description("This is a description of my property")]
public string MyProperty { get; set;}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

.NET comes with a range of build in attributes, among these are:

Custom attributes

It's possible to define your own attributes. This done by creating a class which inherits from Attribute,

using System;
using System.Reflection;
using System.ComponentModel;
using System.Collections.Generic;
class Program{
static void Main()
{
ShowTaxonomyAttribute(typeof(Wolf));
ShowTaxonomyAttribute(typeof(Human));
}
static void ShowTaxonomyAttribute(Type type)
{
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(type);
foreach (System.Attribute attr in attrs)
{
if (attr is Taxonomy)
{
Taxonomy t = (Taxonomy)attr;
System.Console.WriteLine(t);
}
else
{
Console.WriteLine($"Non-taxonomy attribute: {attr.TypeId}");
}
}
}
}
[Taxonomy("Eukarya", Kingdom = "Animala", Specie = "Vulpes vulpes")]
public class Wolf
{
public void MakeASound()
{
Console.WriteLine("Wooooooww!");
}
}
[Description("This is a human")]
[Taxonomy("Eukarya", Kingdom = "Animala", Phylum = "Chordata", Class = "Mammalia", Order= "Primates", Genus ="Homo", Specie = "Homo sapiens", Family = "Hominidae")]
public class Human
{
public void MakeASound()
{
Console.WriteLine("Hallo world");
}
}
// Custom Taxonomy attribute
[System.AttributeUsage(System.AttributeTargets.Class)]
public class Taxonomy : Attribute
{
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content