Skip to content

Instantly share code, notes, and snippets.

@frankhale
Created May 23, 2012 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankhale/2773248 to your computer and use it in GitHub Desktop.
Save frankhale/2773248 to your computer and use it in GitHub Desktop.
Simple C# Reflection Example
using System;
using System.Linq;
using System.Reflection;
namespace ReflectionExample
{
[AttributeUsage(AttributeTargets.Method)]
class Foo : Attribute
{
public string Bar { get; private set; }
public Foo(string bar)
{
Bar = bar;
}
}
class A
{
[Foo("Hello,World")]
public void Bar()
{
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
MethodInfo m = a.GetType().GetMethods().FirstOrDefault(x => x.Name == "Bar");
if (m != null)
{
Foo f = (Foo)m.GetCustomAttributes(false).FirstOrDefault(x => x.GetType() == typeof(Foo));
if (f != null)
{
Console.WriteLine(f.Bar);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment