Search code examples
c#reflectioncode-reuse

Using System.Attribute class


I got myself in a situation where using the System.Attribute class seemed (at first glance) to be a good idea.

I have an object to be printed in my application, and I need a label before each property (or just a string before it). I could put each property hardcoded like:

Console.WriteLine("Color:"+obj.color);
Console.WriteLine("Size:"+obj.size);

And so on for each property. But instead of it, I was trying to create a code where this 'label' doesn't needed to be hardcoded, so I could print every property dynamically.

I got something like that, using System.Attribute class:

public class MyObject 
{
    [MyCustomLabel("Color:")]
    public string Color;

    [MyCustomLabel("Size:")]
    public string Size;
    //etc...
}

So here comes my problem: retrieving this Attribute's value is not impossible, but it's not friendly since I had to use some reflection for it.

I'm not really scared of using reflection, but it seemed that I was using attributes for something that it wasn't created for.

I wonder where are the best places for using attributes, and if this is really a situation for using it.


Solution

  • Attributes and reflection go hand in hand. With the exception of some compiler/runtime attributes, there's no way to use them with out reflecting over the code.

    That said, your approach is reasonable, and you might want to take a look at the attributes in the System.ComponentModel namespace which have a number of classes to decorate properties with useful metadata.