Reflection

Accessing Attributes by Using Reflection (C#)

The fact that you can define custom attributes and place them in your source code would be of little value without some way of retrieving that information and acting on it. By using reflection, you can retrieve the information that was defined with custom attributes. The key method is GetCustomAttributes, which returns an array of objects that are the run-time equivalents of the source code attributes. This method has several overloaded versions. For more information, see Attribute.

An attribute specification such as:C#Copy

[Author("P. Ackerman", version = 1.1)]  
class SampleClass  

Why should I use it?

Reflection is a C # language mechanism for accessing dynamic properties of objects at run time. Reflection is typically used to obtain information about the dynamic object type and the object attribute values. In REST application, for example, reflection could be used to iterate through the serialized response object.

Observations

Reflection allows code to access information about assemblies, modules, and types at run time (program execution). This can then be used to dynamically create, modify, or access types. The types include properties, methods, fields, and attributes.

using System;
using System.Linq;
using System.Reflection;

namespace Reflection
{
    class Program
    {
        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly(); 
            Console.WriteLine(assembly.FullName);

            var types = assembly.GetTypes();
            foreach (var type in types)
            {
                Console.WriteLine($"The type name is: {type.Name}");
                var props = type.GetProperties();
                foreach (var prop in props)
                {
                    Console.WriteLine($"\tThe property is: {prop.Name} Property Type: {prop.PropertyType}");
                }

                var fields = type.GetFields();
                foreach (var field in fields)
                {
                    Console.WriteLine($"\tThe field is: {field.Name} Field Type: {field.FieldType}");
                }

                var methods = type.GetMethods();
                foreach (var method in methods)
                {
                    Console.WriteLine($"The method is: {method.Name}");
                }
            }

            var sample = new Sample { Name = "Albr", Age = 30 };
            var sampleType = typeof(Sample);

            var nameProperty = sampleType.GetProperty("Name");
            if (nameProperty != null)
            {
                Console.WriteLine($"Property name: {nameProperty.Name}");
                Console.WriteLine($"Property value: {nameProperty.GetValue(sample)}");
            }

            var myMethod = sampleType.GetMethod("MyMethod");
            myMethod.Invoke(sample, null);

            Console.WriteLine("==========================");
            var attributeTypes = assembly.GetTypes().Where(t => t.GetCustomAttributes<MyClassAttribute>().Count() > 0);
            foreach (var type in attributeTypes)
            {
                Console.WriteLine($"The type is: {type.Name}");

                var methodsCustomAttributes = type.GetMethods().Where(m => m.GetCustomAttributes<MyMethodAttribute>().Count() > 0);
                foreach (var method in methodsCustomAttributes)
                {
                    Console.WriteLine($"The method name is: {method.Name}");
                }
            }

            Console.ReadLine();
        }
    }

    [MyClass]
    public class Sample
    {
        public string Name { get; set; } // This is a property
        public int Age; // this is a field

        [MyMethod]
        public void MyMethod()
        {
            Console.WriteLine("Hello from method");
        }

        [MyMethod]
        public void MyMethod2() { }
    }

    [AttributeUsage(AttributeTargets.Class)]
    public class MyClassAttribute : Attribute { }

    [AttributeUsage(AttributeTargets.Method)]
    public class MyMethodAttribute : Attribute { }
}

Output result:

You can also verify this information using the Object Browser in VS2019.

The Object Browser allows you to browse through all available objects in your project and see their properties, methods and events. In addition, you can see the procedures and constants that are available from object libraries in your project. You can easily display online Help as you browse. You can use the Object Browser to find and use objects that you create, as well as objects from other applications.

Last updated