Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to implement custom attributes in dotnet/.NET?

I don't really understand attributes. I've read all kinds of books & posts on them, but I just don't get it.

Since I don't understand them, I also don't understand how to effectively use them.

1) Can you give me a good definition of what an attribute is & what it's used for?

2) Can you give me a good code example in C# of how to make and consume a custom attribute?

like image 419
IAmAN00B Avatar asked Jun 10 '09 14:06

IAmAN00B


3 Answers

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.

like image 172
Andrew Hare Avatar answered Oct 21 '22 08:10

Andrew Hare


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

like image 22
cjk Avatar answered Oct 21 '22 09:10

cjk


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
}
like image 3
Vasu Balakrishnan Avatar answered Oct 21 '22 08:10

Vasu Balakrishnan