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:

  1. public enum PurposeKind
  2. {
  3. Development,
  4. [Description("Functional Test")]
  5. Test,
  6. [Description("Unit Test")]
  7. UnitTest,
  8. }
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:
  1. static void Main(string[] args)
  2. {
  3. var valuesAndDescriptions = new Dictionary<PurposeKind, string>();
  4. // gets the Type that contains all the info required
  5. // to manipulate this type
  6. Type enumType = typeof(PurposeKind);
  7. // I will get all values and iterate through them
  8. var enumValues = enumType.GetEnumValues();
  9. foreach (PurposeKind value in enumValues)
  10. {
  11. // with our Type object we can get the information about
  12. // the members of it
  13. MemberInfo memberInfo =
  14. enumType.GetMember(value.ToString()).First();
  15. // we can then attempt to retrieve the
  16. // description attribute from the member info
  17. var descriptionAttribute =
  18. memberInfo.GetCustomAttribute<DescriptionAttribute>();
  19. // if we find the attribute we can access its values
  20. if (descriptionAttribute != null)
  21. {
  22. valuesAndDescriptions.Add(value,
  23. descriptionAttribute.Description);
  24. }
  25. else
  26. {
  27. valuesAndDescriptions.Add(value, value.ToString());
  28. }
  29. }
  30. }
Results:

    Development,Development
    Test,Functional Test
    UnitTest,Unit Test

See System.Type on MSDN for a reference of reflection methods.