Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
You can create your own custom attributes by defining an attribute class, a class that derives directly or indirectly from Attribute, which makes identifying attribute definitions in metadata fast and easy. Suppose you want to tag types with the name of the programmer who wrote the type. You might define a custom Author
attribute class:
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)
]
public class AuthorAttribute : System.Attribute
{
private string Name;
public double Version;
public AuthorAttribute(string name)
{
Name = name;
Version = 1.0;
}
}
The class name AuthorAttribute
is the attribute's name, Author
, plus the Attribute
suffix. It's derived from System.Attribute
, so it's a custom attribute class. The constructor's parameters are the custom attribute's positional parameters. In this example, name
is a positional parameter. Any public read-write fields or properties are named parameters. In this case, version
is the only named parameter. Note the use of the AttributeUsage
attribute to make the Author
attribute valid only on class and struct
declarations.
You could use this new attribute as follows:
[Author("P. Ackerman", Version = 1.1)]
class SampleClass
{
// P. Ackerman's code goes here...
}
AttributeUsage
has a named parameter, AllowMultiple
, with which you can make a custom attribute single-use or multiuse. In the following code example, a multiuse attribute is created.
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // Multiuse attribute.
]
public class AuthorAttribute : System.Attribute
{
string Name;
public double Version;
public AuthorAttribute(string name)
{
Name = name;
// Default value.
Version = 1.0;
}
public string GetName() => Name;
}
In the following code example, multiple attributes of the same type are applied to a class.
[Author("P. Ackerman"), Author("R. Koch", Version = 2.0)]
public class ThirdClass
{
// ...
}
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Events
17 Mar, 9 pm - 21 Mar, 10 am
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowTraining
Module
Get started with classes and objects in C# - Training
Learn how to create classes and instantiate objects that expose encapsulated field data by using class definitions, constructors, and the 'new' operator.