Reflection uses the object of type Type that describes assemblies, modules and types.
Using reflection, it is possible to do many things, for example:
- Dynamically create object instances.
- Dynamically invoke methods.
- Check if an object implements an interface.
- Manipulate attributes set on objects.
- Mock values for testing.
- Retrieve debug information.
These are just a few things you can do with it. In this article I will show a simple example of how to use it to get descriptions of enums.
Let us say you want to display an enum in a dropdown. However, you want to have the code and description rather than just displaying the code. You can annotate your enum with the description attribute:
- public enum PurposeKind
- {
- Development,
-
- [Description("Functional Test")]
- Test,
-
- [Description("Unit Test")]
- UnitTest,
- }
And to get the description we can use reflection. I will be getting the value and description and then I will add it to a dictionary as in the following:
- static void Main(string[] args)
- {
- var valuesAndDescriptions = new Dictionary<PurposeKind, string>();
-
-
-
- Type enumType = typeof(PurposeKind);
-
-
- var enumValues = enumType.GetEnumValues();
-
- foreach (PurposeKind value in enumValues)
- {
-
-
- MemberInfo memberInfo =
- enumType.GetMember(value.ToString()).First();
-
-
-
- var descriptionAttribute =
- memberInfo.GetCustomAttribute<DescriptionAttribute>();
-
-
- if (descriptionAttribute != null)
- {
- valuesAndDescriptions.Add(value,
- descriptionAttribute.Description);
- }
- else
- {
- valuesAndDescriptions.Add(value, value.ToString());
- }
- }
- }
Results:
Development,Development
Test,Functional Test
UnitTest,Unit Test
See System.Type on MSDN for a reference of reflection methods.