Attributes add extra information to your code. Attribute targets tell where you can put these attributes, like on a class or a method.
0
0
Attribute targets and usage in C Sharp (C#)
Introduction
When you want to mark a class to show it has special behavior.
When you want to add notes to a method for tools or frameworks.
When you want to control where an attribute can be applied to avoid mistakes.
When you want to create your own attribute and limit its usage to certain code parts.
Syntax
C Sharp (C#)
[AttributeUsage(AttributeTargets.Target1 | AttributeTargets.Target2, AllowMultiple = true|false)] public class MyAttribute : Attribute { // attribute code here }
AttributeTargets is a set of options like Class, Method, Property, etc.
AllowMultiple controls if you can put the same attribute more than once on the same target.
Examples
This attribute can only be used on classes.
C Sharp (C#)
[AttributeUsage(AttributeTargets.Class)] public class MyClassAttribute : Attribute { }
This attribute can be used on methods and properties, and you can use it multiple times on the same item.
C Sharp (C#)
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class MyMultiUseAttribute : Attribute { }
This attribute can be used anywhere.
C Sharp (C#)
[AttributeUsage(AttributeTargets.All)] public class MyGeneralAttribute : Attribute { }
Sample Program
This program defines an attribute that can only be used on methods. It marks one method with it and runs that method.
C Sharp (C#)
using System; [AttributeUsage(AttributeTargets.Method)] public class RunMeAttribute : Attribute { } public class TestClass { [RunMe] public void MyMethod() { Console.WriteLine("MyMethod is running."); } // This would cause a compile error if uncommented because RunMe is only for methods // [RunMe] // public int MyProperty { get; set; } } class Program { static void Main() { var test = new TestClass(); test.MyMethod(); } }
OutputSuccess
Important Notes
If you don't specify AttributeUsage, your attribute can be used anywhere and only once per target.
Use AttributeTargets flags combined with | to allow multiple target types.
Setting AllowMultiple to true lets you put the same attribute many times on one target.
Summary
Attribute targets control where an attribute can be applied.
Use AttributeUsage to set targets and if multiple uses are allowed.
This helps keep your code clear and prevents wrong attribute usage.