reflection_attribute_class.htm

using System;
using System.Reflection;
//csc reflection_attribute_class.cs
namespace CustomAttrCS {
public enum automobile
{
// types
SUV ,
Sedan,
HutchBack
}
// A custom attribute to allow a target to have a motorized.
public class class_auto : Attribute {
// The constructor is called when the attribute is set.
public class_auto(automobile x) {
auto = x;
Console.WriteLine("Constructor ");
}
// enum internal variable used by machine..
protected automobile auto;
//enumm machine is called from the instances
//enum read and write
public automobile machine
{
get { return auto; }
set { auto = machine; }
}
}
//providing attributes to each method
class class_at_setter {
[class_auto(automobile.SUV )]
public void SUVMethod() {Console.WriteLine("Base is high ");}
//class_name(enum.enum_field)
[class_auto(automobile.Sedan)]
public void SedanMethod() {Console.WriteLine("Base is low");}

[class_auto(automobile.HutchBack)]
public void HutchBackMethod() {Console.WriteLine("Base is low");}
}

class DemoClass {
static void Main(string[] args) {
class_at_setter testClass = new class_at_setter();
Type type = testClass.GetType();
string str = "";
// Iterate methods
foreach(MethodInfo mi in type.GetMethods()) {
// Iterate Attributes for each method.
foreach (Attribute attr in
Attribute.GetCustomAttributes(mi)) {
// Get Type of attribute.
if (attr.GetType() == typeof(class_auto)){
str = mi.Name.ToString();
Console.WriteLine( "Method {0} has {1} attribute.", mi.Name, ((class_auto)attr).machine);
if(str == "SUVMethod"){ testClass.SUVMethod();}
if(str == "SedanMethod"){ testClass.SedanMethod();}
if(str == "HutchBackMethod"){ testClass.HutchBackMethod();}
}
}
}
Console.ReadLine();
}
}
}