" Writing your own custom attributes"

Attributes in C# are classes that inherit from System.Attribute
. You use them to decorate code elements like classes, methods, properties. Straight to the point best practice is for us to utilize this is to limit it’s decoration capability.
Here we create a normal constructor and a parameter of attribute targets telling where we can decorate our attributes and if we are allowing it to be of multiples.
Peek the definition of the AttributeTargets
promise it won’t hurt you, to learn more about your codebase for once, and not rely on AI :). It can pretty much be decorated on all of your every day code usage except for records.
I don’t know why on C# attribute target there is no records. Maybe it’s because “records are just classes with less boiler plate code” and with additional methods that you can utilize , a value based type and a different IEquatable. You can check my previous blog about that: (click here to navigate on my previous blog about records) So technically speaking we can decorate record using the custom attribute that targets a class.
It works just like we expected.
Now moving on here is an example on how we can retrieve the attributes using the isDefined of the Attribute. but here isDefined says that it returns true if a custom attribute of a type is applied to the element.
That’s why we first get the class first and then pass that type on the isDefined method next is supplying the customAttribute that we are retrieving.
Now we can check that on all the elements that is decorated by that attribute we can apply a logging, validation etc. Also added to that we do have a GetCustomAttributes that returns a collection.
A real world example is where we want to persist a specific event on our database. So this will not log events that has been decorated by the IgnoreEventAttribute. Isnt’ it elegant?
Well we can also achieve this by using marker interface.
And then decorating the event with the interface.
Finally check if the notification / event is an ILoggableEvent.
As you can see same intention but different code implementation. But on my own preference I prefer using the [IgnoreEvent] attribute decorating the class metadata.
For ending this blog, i just want to tell that I know it’s easy to prompt our way to ship the feature that we are creating, shipping tickets much more faster with AI, but please let us take some time to really understand the code that we are writing line by line. Not on the really lowest level type of understanding but somehow have that grasp. It helps me to be confident on my code before pushing it into our repository.
Subscribe to my newsletter
Read articles from Juan Miguel Nieto directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Juan Miguel Nieto
Juan Miguel Nieto
A software developer trying to write organic blogs.