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,
- }
- static void Main(string[] args)
- {
- var valuesAndDescriptions = new Dictionary<PurposeKind, string>();
- // gets the Type that contains all the info required
- // to manipulate this type
- Type enumType = typeof(PurposeKind);
- // I will get all values and iterate through them
- var enumValues = enumType.GetEnumValues();
- foreach (PurposeKind value in enumValues)
- {
- // with our Type object we can get the information about
- // the members of it
- MemberInfo memberInfo =
- enumType.GetMember(value.ToString()).First();
- // we can then attempt to retrieve the
- // description attribute from the member info
- var descriptionAttribute =
- memberInfo.GetCustomAttribute<DescriptionAttribute>();
- // if we find the attribute we can access its values
- if (descriptionAttribute != null)
- {
- valuesAndDescriptions.Add(value,
- descriptionAttribute.Description);
- }
- else
- {
- valuesAndDescriptions.Add(value, value.ToString());
- }
- }
- }
Development,Development
Test,Functional Test
UnitTest,Unit Test
See System.Type on MSDN for a reference of reflection methods.

Brendon MascarenhasPosted Dec 2, 2019, 10:54 AM
Nice article
Sonu ChaudharyPosted Feb 25, 2016, 7:15 AM
nice article
MichePosted Jun 1, 2015, 11:19 AM
Quite Useful
Santhakumar MunuswamyPosted May 31, 2015, 11:17 PM
Thanks for nice one