Can InvokeMethod be used as optional parameters?

I have base class A in a project

There are many subclasses that inherits from A

public class A
{
    public void Process(string myString1, int myInt1   )
        {
            Type type = this.GetType();
            type.InvokeMember("ImAChildMethod", System.Reflection.BindingFlags.InvokeMethod
                                                | System.Reflection.BindingFlags.NonPublic 
                                                | System.Reflection.BindingFlags.Instance,
                                                null, 
                                                this, 
                                                new object[] { myString1, myInt1  });
        }
}

Subclass :

public class B:A
{
   private void ImAChildMethod(string myString, int myInt )
    {
     Console.WriteLine (myInt + ","+myString);
    }
}

So when I Exeucte :

new B().Process("aaa",15); I get

15,aaa

Great.

Days have passed and now we need to send — not:

new object[] { myString1, myInt1 }

but

new object[] { myString1, myInt1 , MyDateTime }

(however , not all subclasses uses this datetime parameter)

Ok so we changed (at the specific places) from :

 private void ImAChildMethod(string myString, int myInt )

to

 private void ImAChildMethod(string myString, int myInt ,DateTime myDateTime )

So where is the problem ?

It caused exception in places that we did not change.

Question

I don't want to go through all sub classes and add this parameter of datetime. ( not all subclasses uses this parameter)

Is there a way to "pre-recognize" that ImAChildMethod does / doesn't have ,DateTime myDateTime and if it has : use it , and if it doesn't - ignore the new parameter ?

Nb

I'm pretty sure that I'll have to go through subclasses and add optional parameter...but I might be wrong ?

Jon Skeet
people
quotationmark

Optional parameters are really a compile-time feature - the CLR and framework have very little to do with them, other than to make the information available via reflection.

So while you can detect the fact that a parameter is optional (with ParameterInfo.IsOptional) and get the default value (with ParameterInfo.DefaultValue) you need to do that explicitly - InvokeMember doesn't do it for you.

You may want to write a helper method which is effectively like InvokeMember, but handles optional parameters... just bear in mind that if you only accept a name, you'll get into the awkward business of overload resolution. You might want to restrict it to only work with names with a single overload, just for simplicity.

people

See more on this question at Stackoverflow