C# Refresh
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;}
}
Enter to Rename, Shift+Enter to Preview
.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,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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)]
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content