Attribute Execution

CSharp · Console

/Program.cs

	using System;
	using System.Linq;
	
	public class HelloWorldAttribute : System.Attribute  
	{  
		private string _someString;
		
	
		public HelloWorldAttribute(string text)  
		{  
			_someString = text;
		}  
		
		public void MyAttributeMethod()
		{
			Console.WriteLine("HelloWorldAttribute says '{0}'.", _someString);
		}
	}  
	
	public class MyClass
	{
		[HelloWorld("This is a test!!")]
		public void MyClassMethod(string text)
		{
			Console.WriteLine("MyClassMethod says '{0}'", text);
		}
	}
	
	
	public class Program
	{
		public static void Main()
		{
			//By itself, the attribute does nothing
			var c = new MyClass();
			c.MyClassMethod("Main call");
			
			//You need to write code to detect the attribute and make it do something
			typeof(MyClass)
				.GetMethod("MyClassMethod")
				.GetCustomAttributes(true)
				.OfType<HelloWorldAttribute>()
				.First()
				.MyAttributeMethod();
			c.MyClassMethod("Main call");
		}
	}
;