1
Vote

MethodUtils - Invoke method without parameters

description

When I need to invoke a method, I can't pass parameters. I have attached a .cs file with a solution to fix this:
 
                                      /// --------------------------------------------------------------------
    /// <summary>
    /// Invoke an method of an object if it exists
    /// </summary>
    /// <param name="srcObj">the object in which the method to invoke</param>
    /// <param name="methodName">method name to invoke</param>
    /// <returns>the value return after invoking a method</returns>
    /// <exception cref="ArgumentNullException">if srcobj is null</exception>
                                      /// <param name="parameters">Parameters passed to the method</param>
    /// <exception cref="ArgumentException">if methodName is null or empty</exception>
    /// --------------------------------------------------------------------
    public static object InvokeMethod(Object srcObj, string methodName, params object[] parameters)
    {
 
        if (srcObj == null)
            throw new ArgumentNullException("srcObj");
 
        if ((methodName == null) || (methodName.Length < 1))
            throw new ArgumentException("methodName cannot be null or empty");
 
        MethodInfo methodInfo = srcObj.GetType().GetMethod(methodName);
 
        if (methodInfo == null)
            return null;
 
        return methodInfo.Invoke(srcObj, parameters);
    }
 
Bye.
 
RFL

file attachments

comments