MethodBase.Invoke Method

Viewed 1793

I am trying to understand how reflection works so my question is that when I want to invoke some method in assembly why do I send method parameters as an object array and not as a string?

For example I want to invoke this method it gets string parameter but I send arguments as a object array. As far as I know object cant be converted into a string so how it converts it?

public string Display(string Name)
    {
        return Name;
    }
1 Answers

MethodBase.Invoke allows calling methods with many parameters of arbitrary types.

MethodBase.Invoke allows you to call any method with any paramaters, including your Display(string Name) but also MyMethod(int val) and object[] params give callers of Invoke the ability to provide parameters of any type.


Re:

as far as I know object cant be converted into a string so how it converts it

What is happening here is boxing, please check out Boxing and Unboxing (C# Programming Guide).

If you try to call your method with parameters with incorrect types it will not work.

The code snippet below will produce the following output.

MagicClass.ItsMagic() returned: 900, type: System.Int32
Object of type 'System.String' cannot be converted to type 'System.Int32'.
public class MagicClass
{
    private int magicBaseValue;
    public MagicClass() { magicBaseValue = 9; }
    public int ItsMagic(int preMagic) { return preMagic * magicBaseValue; }
}

public static void Main(string[] args)
{
    var m = new MagicClass();

    MethodInfo magicMethod = m.GetType().GetMethod("ItsMagic");
    object magicValue = magicMethod.Invoke(m, new object[] { 100 });

    Console.WriteLine($"MagicClass.ItsMagic() returned: {magicValue}, type: {magicValue.GetType()}");

    try
    {
        object magicValue2 = magicMethod.Invoke(m, new object[] { "One hundred" });
    } catch (ArgumentException ex) { Console.WriteLine(ex.Message); }
}

MagicClass is borrowed from MethodBase.Invoke Method 's doco.

Related