.NET Course
  • Welcome developers
  • LINQ
    • Advanced c# overview
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Anonymous Types
      • Ref vs Out
      • Task
      • TaskFactory
      • Asynchronous programming with async and await
      • Abstract class VS Interface
      • Inheritance, Composition and Aggregation in C#
    • LINQ Tutorial
      • Loading Related Entities
      • Lambda Expression
      • Standard Query Operators
    • Testing ASP.NET Core
      • Implementing unit tests for ASP.NET Core Web APIs
    • Software development principles
      • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • SOLID: The First 5 Principles of Object Oriented Design
  • Helping links
    • SonarQube installation and tutorial for .net core projects
  • C# .NET Interview Questions
    • Ultimate C# Interview questions
      • Part 4
      • Part 3
      • Part 2
      • Part 1
  • Unit test .NET Core xUnit & MOQ
    • Content
      • Snippets
      • Traits
Powered by GitBook
On this page
  • Accessing Attributes by Using Reflection (C#)
  • Why should I use it?

Was this helpful?

  1. LINQ
  2. Advanced c# overview

Reflection

PreviousAttributesNextDelegates

Last updated 3 years ago

Was this helpful?

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 .

An attribute specification such as:

[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 { }
}
Attribute