So, in part 2 we looked at setting up a Visual Studio solution to host the project. We split it up into four parts:
- Attribute Discovery
- Custom Attributes
- Attribute User
- Host executable
In this part we’ll look at our Custom Attributes project. So, if you haven’t already created a solution project then do so now. Create a new Blank Solution under ‘Other Project Types -> Visual Studio Solutions’. When created, add a new C# Class Library to the solution. I’ve called mine JamesWisemanAttributes, but you can name yours in any way you want.
Let’s dive straight into the code:
namespace JamesWisemanAttributes { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class CustomClassLevelAttribute : Attribute { public CustomClassLevelAttribute() {} } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class CustomMethodLevelAttribute : Attribute { public CustomMethodLevelAttribute() {} } }
We should observe the following things about our code:
- They are simple classes derived from System.Attribute
- The constructor actually does nothing at the moment so could be omitted. (Later it will do something, which is why it’s included here)
- They are themselves decorated with attributes denoting their usage. The class attribute has a Class AttributeTarget and the method’s attribute denotes that it’s for a method only. We could combine these with an or ‘|’ operator.
And that’s really it. There’s nothing groundbreaking about this – we’re just setting up our projects and setting the scene.
Next up, we look at AttributeUser, the class that will use our attribute.