How do I dynamically pass string methods to be applied to strings at run time. ex.
Private String Formatting(String Data, String Format)
When we pass String S1 = "S1111tring Manipulation"
and format = Remove(1,4)
- behind the scenes it becomes S1.Remove(1,4)
resulting in "String Manipulation"
or if we pass String S1 = "S1111tring Manipulation"
and format = ToLower()
behind the scene it becomes S1.ToLower()
resulting in "s1111tring manipulation"
I should be able to pass any valid method like PadLeft(25,'0')
, PadRight
, Replace
etc...
I would appreciate a complete example
This is what I have tried and it does not work
using System.Reflection;
string MainString = "S1111tring Manipulation";
string strFormat = "Remove(1, 4)";
string result = DoFormat(MainString, strFormat);
private string DoFormat(string data, string format)
{
MethodInfo mi = typeof(string).GetMethod(format, new Type[0]);
if (null == mi)
throw new Exception(String.Format("Could not find method with name '{0}'", format));
return mi.Invoke(data, null).ToString();
}
throws an error (Could not find method with name 'Remove(1, 4)') - so I am not sure how to proceed