Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a property or method using an attribute name

Let's say I have a class that looks like this:

public class CallByAttribute
{
    [CodeName("Foo")]
    public string MyProperty { get; set; }

    [CodeName("Bar")]
    public string MyMethod(int someParameter)
    {
         return myDictionary[someParameter];
    }
}

How would I call these two properties or methods, using CodeName instead of the property or method name?

like image 796
Robert Harvey Avatar asked Sep 14 '10 03:09

Robert Harvey


People also ask

What are attributes used for in C#?

Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element.

What are attributes and reflections C#?

Attribute ReflectionReflection is a set of . NET APIs that facilitate retrieving metadata from C# attributes. Reflection is used to retrieve attributes associated with an attribute target. This code calls GetCustomAttributes to list the attribute type names for the Id property.

How would you determine if a class has a particular attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);


1 Answers

Method 1:

public static TOutput GetPropertyByCodeName<TOutput>(this object obj, string codeName)
{
    var property = obj.GetType()
                      .GetProperties()
                      .Where(p => p.IsDefined(typeof(CodeNameAttribute), false))
                      .Single(p => ((CodeNameAttribute)(p.GetCustomAttributes(typeof(CodeNameAttribute), false).First())).Name == codeName);

    return (TOutput)property.GetValue(obj, null);
}

Note: This will throw if no property exists with the specified codeName or if multiple properties share the same codeName.

Usage:

CallByAttribute obj= ...
string myProperty = obj.GetPropertyByCodeName<string>("Foo");

Method 2:

If you are on C# 4, you can write your own System.Dynamic.DynamicObject that can route dynamic calls to the right member.

This will allow for cleaner syntax. For example, you should be able to accomplish something that allows:

CallByAttribute obj= ...
dynamic objectByCodeName = new ObjectByCodeName(obj);
objectByCodeName.Foo = "8";
objectByCodeName.Bar();
like image 118
Ani Avatar answered Sep 30 '22 01:09

Ani