Type, MethodInfo, activation, custom attributes
Get Type objects, locate MethodInfo, invoke methods, create instances with Activator, and define/read custom attributes.
Overview
Goal: Use reflection safely.
- Get Type
- Find MethodInfo
- Create via Activator
- Define & read attributes
Get Type
Get Type from typeof, an instance with GetType(), or by name via Type.GetType.
using System;
public class Sample { }
public class Program
{
public static void Main(string[] args)
{
// 1) From a compile-time type
Type t1 = typeof(Sample);
// 2) From an instance
Sample s = new Sample();
Type t2 = s.GetType();
// 3) From a full name (needs assembly-qualified name for external types)
Type t3 = Type.GetType("System.String");
Console.WriteLine(t1.Name + ", " + t2.FullName + ", " + (t3 == null ? "null" : t3.Name));
}
}
All lessons in this course
- Type, MethodInfo, activation, custom attributes
- Source-level info (Caller attributes)
- Light metaprogramming scenarios