Skip to content

Instantly share code, notes, and snippets.

@trbngr
Created August 6, 2011 18:08
Show Gist options
  • Save trbngr/1129580 to your computer and use it in GitHub Desktop.
Save trbngr/1129580 to your computer and use it in GitHub Desktop.
public class Program
{
private static void Main()
{
var instance = new SomeClass
{
SomePropertyWithAttribute = "I have an attribute",
SomeProperty = "I don't have an attribute"
};
Inspect(instance);
Console.ReadKey(false);
}
private static void Inspect(SomeClass instance)
{
var type = instance.GetType();
foreach (var property in type.GetProperties())
{
var attribute = property.GetCustomAttributes(typeof(MyAttribute), false)
.Cast<MyAttribute>()
.FirstOrDefault();
if(attribute != null)
{
Console.Out.WriteLine("{0} = {1}", attribute.GetType().Name, attribute.Value);
}
Console.Out.WriteLine("{0} = {1}", property.Name, property.GetValue(instance, null));
Console.Out.WriteLine("");
}
}
}
public class SomeClass
{
public string SomeProperty { get; set; }
[MyAttribute("MyValue")]
public string SomePropertyWithAttribute { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
public MyAttribute(string value)
{
Value = value;
}
public string Value { get; private set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment