.NET/C#
  • ASP.NET Core Overview
  • ASP.NET Core API tutorial
    • How to create ASP.NET Core C# API tutorial
      • launchSettings
      • Install swagger
        • Swagger best practices
      • Run the app
      • Fix CORS problem
      • Add AutoMapper
      • Add JWT reference
      • Add .gitignore
      • Basic structure & EF Core
      • AddSingleton
    • Loading Related Entities
  • Unit test controller logic in ASP.NET Core
    • Unit testing controllers
  • .NET Q&A
    • dotnet try
    • LINQ
      • LINQ Query Syntax
      • Lambda Expression
      • Standard Query Operators
  • .NET C# Interview questions
    • C# - .NET interview questions and answers [Part 1]
    • C# - .NET interview questions and answers [Part 2]
    • C# Interview questions [Part 3] General questions
  • C#
    • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • Project architecture
    • C# Advanced review
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Ref vs Out
      • Task
        • TaskFactory Class
  • MySQL
    • MySQL Lerning
      • SELECT
      • ORDER BY
      • WHERE
      • DISTINCT
      • IN
      • BETWEEN
      • Join
      • INNER JOIN
      • LEFT JOIN
      • RIGHT JOIN
      • GROUP BY
      • Subquery
      • UNION
    • Stored Procedures
      • CREATE PROCEDURE
  • Versioning API, MongoDB and ci-cd
    • Create a web API with ASP.NET Core and MongoDB
    • REST API versioning with ASP.NET Core
    • Design a CI/CD pipeline using Azure DevOps
      • Create a CI/CD pipeline for GitHub repo using Azure DevOps Starter
  • TFS & TFCV
    • What is Team Foundation Version Control
      • Develop and share your code in TFVC using Visual Studio
      • Suspend your work and manage your shelvesets
    • Newtonsoft Json.NET
      • Serializing and Deserializing JSON
  • MS-SQL
    • Quick tutorial
      • Add new column to a table
      • LEFT/RIGHT Reverse operator
      • Dates (Transact-SQL)
      • CAST and CONVERT (Transact-SQL)
      • Types of JOIN
      • Our first Left Outer Join
      • CROSS JOIN
Powered by GitBook
On this page
  • Accessing Attributes by Using Reflection (C#)
  • Why should I use it?

Was this helpful?

  1. C#
  2. C# Advanced review

Reflection

PreviousAttributesNextDelegates

Last updated 4 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: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 allows you to browse through all available objects in your and see their , and events. In addition, you can see the and that are available from 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.

Attribute
Object Browser
project
properties
methods
procedures
constants
object libraries