What are reflections in C#?

CsharpProgrammingServer Side Programming

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace.

The MemberInfo object of the System. Reflection class needs to be initialized for discovering the attributes associated with a class.

In the below example we have set the object of the target class −

System.Reflection.MemberInfo info = typeof(MyClass);

Here is the example −

Example

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
   public readonly string Url;

   public string Topic { // Topic is a named parameter
   get {
      return topic;
   }

   set {
      topic = value;
   }
}

public HelpAttribute(string url) { // url is a positional parameter
   this.Url = url;
}

private string topic;
}

[HelpAttribute("Information on the class MyClass")]
   class MyClass {

}

namespace AttributeAppl {
   class Program {
      static void Main(string[] args) {
         System.Reflection.MemberInfo info = typeof(MyClass);
         object[] attributes = info.GetCustomAttributes(true);
         for (int i = 0; i < attributes.Length; i++) {
            System.Console.WriteLine(attributes[i]);
         }

         Console.ReadKey();
      }
   }  
}
raja
Published on 13-Aug-2018 07:00:55
Advertisements