Niklas
Niklas

Reputation: 13145

Get property ToString with formatting

Using reflection I can do ToString on a property. But is there a way to supply a formatting while doing this?

public static object GetCustomValue(object src, string propName)
{
    return src.GetType().GetMethod(propName).GetValue(src, null);
}

Calling the function like this works fine

GetCustomValue(obj, "ToString")

But I would like to call it with

GetCustomValue(obj, "ToString(\"MMM\")")

Is it possible to add formatting to the ToString when calling the GetMethod in my function?

Upvotes: 3

Views: 545

Answers (2)

Alexandre Borela
Alexandre Borela

Reputation: 1626

If your ToString accepts paramters (the default one doesn't) add an extra optional parameter:

public static Object GetCustomValue (object Target, string MethodName, String Format = null)
{
    // Gets the ToString method that accepts a string as the parameter and invoke it.
    return Target.GetType ()
        .GetMethod (MethodName, new [] {typeof (String)})
        .Invoke (Target, new Object[] {Format});
}

This way you can call it:

GetCustomValue (obj, "ToString", "MMM");

Upvotes: 3

Nalaka
Nalaka

Reputation: 1185

Yes, you can use out of the method name .ToString(format);

GetPropertyValue(obj, "ToString").ToString(format); 

Upvotes: 1

Related Questions