Search code examples
c#reflectionconventions

using attributes vs conventional getting properties


I need to find all properties of a specific object which are not readonly and based on their type do something I mean if the type of property is int i need to do sth and if it is string i should do something else

using reflection and get this type and conventionally i can create an object which can do what I want for example if the property type is Int , I can create an instance of IntType:IType class

but I have another option: set an attribute for each property and based on these attributes,find suitable IType I just cant decide which one is better?


Solution

  • If all the information you need is already contained in the type of the property, I can't see how introducing a new attribute is a good idea. Aside from anything else, you can easily forget to update the attribute when the data type changes. You start off with:

    [Int32Type]
    int Foo { get; set; }
    

    then find you actually need it to be a long, but forget to change the attribute:

    [Int32Type]
    long Foo { get; set; }
    

    Now you're probably going to be acting incorrectly on it.

    If you're really adding information - e.g. if not all int properties need to be treated the same way - that's a different matter.