Question:
How do I create a custom attribute in dot.net?Do you have a simple sample for attribute creation in c# / dot.net?
Answer:
You simply create a class that inherits from System.Attribute.Follow these steps:
- Create a new class
- Make it derive from System.Attribute
- Specify the usage (does this attribute applies to assembly, class, methods etc.)
Example of a simple marker attribute
using System; [AttributeUsage(AttributeTargets.Property)] public class MarkerAttribute : System.Attribute { // you could add info here }
You could use this attribute in order to mark certain properties in a class.
For example for custom serialization you might want to serialize only properties that are marked with your attribute.
Related: How to discover custom attributes?
No comments:
Post a Comment