What's the best way to implement custom attributes in dotnet/.NET?
I could give you an example but it would pale in comparison to this fine article:
Defining and Using Custom Attribute Classes in C#
The complex, component-style development that businesses expect out of modern software developers requires greater design flexibility than the design methodologies of the past. Microsoft's .NET Framework makes extensive use of attributes to provide added functionality through what is known as "declarative" programming. Attributes enhance flexibility in software systems because they promote loose coupling of functionality. Because you can create your own custom attribute classes and then act upon them, you can leverage the loose coupling power of attributes for your own purposes.
Say you've got a class with a series of properties that you are going to walk through using reflection. Any that are strings may need to be validated to check they are not longer than a certain amount.
You could then create a TextLength
attribute, with a default integer constructor and integer property/field. You could then read your attribute on each string property in your class and compare the length of the property value to the number specified in the attribute.
Code:
public class TextLengthAttribute : Attribute
{
private int length;
public int Length { get { return length; } set { length = value; } }
public TextLengthAttribute(int num) { this.length = num; }
}
public class MyClass
{
[TextLength(10)]
public string Property1;
[TextLength(20)]
public string Property2;
}
public class ClassReader
{
public static void Main()
{
MyClass example = MyClass.GetTestData();
PropertyInfo[] props = typeof(MyClass).GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.ValueType == typeof(String)
{
TextLengthAttribute[] atts =
(TextLengthAttribute)[]prop.GetCustomAttributes(
typeof(TextLengthAttribute), false);
if (prop.GetValue(example, null).ToString().Length >
atts[0].Length)
throw new Exception(prop.name + " was too long");
}
}
}
}
Note: untested
We have a requirement to display Enum Values in a dropdown in a specific sort order. We implemented using Custom Attributes.
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field, AllowMultiple = false)]
public class EnumSortAttribute : Attribute
{
public int SortOrder;
public bool SortByDescription;
}
[EnumSort(SortByDescription=true)]
public enum EnumSortByDescription
{
[Description("enO")]
One = 1,
[Description("2")]
Two = 2,
Three = 3,
[Description("rouF")]
Four = 4
}
public enum EnumCustomSortOrder
{
[EnumSort(SortOrder = 3)]
One = 1,
[EnumSort(SortOrder = 1)]
Two = 2,
[EnumSort(SortOrder = 2)]
Three = 3
}