Creating a custom attribute C# with Example



Creating a custom attribute C# with Example

//1) All attributes should be inherited from System.Attribute 
//2) You can customize your attribute usage (e.g. place restrictions) by using System.AttributeUsage 
Attribute 
//3) You can use this attribute only via reflection in the way it is supposed to be used 
//4) MethodMetadataAttribute is just a name. You can use it without "Attribute" postfix - e.g. 
[MethodMetadata("This text could be retrieved via reflection")]. 
//5) You can overload an attribute constructors 
[System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Class)] 
public class MethodMetadataAttribute : System.Attribute 
{ 
//this is custom field given just for an example 
//you can create attribute without any fields 
//even an empty attribute can be used - as marker 
public string Text { get; set; } 
//this constructor could be used as [MethodMetadata] 
public MethodMetadataAttribute () 
{ 
} 
//This constructor could be used as [MethodMetadata("String")] 
public MethodMetadataAttribute (string text) 
{ 
Text = text; 
} 
} 

0 Comment's

Comment Form