C
C#2mo ago
cypherpotato

can I specify an Type wildcard for GetMethod?

I have both methods:
void DoFoo(string aaa);
void DoFoo(string aaa, string? bbb);
void DoFoo(string aaa);
void DoFoo(string aaa, string? bbb);
I can invoke DoFoo with two parameters through reflection with:
Type[] args = [typeof(string), typeof(string)];
MethodInfo? foo = objType.GetMethod("DoFoo", BindingFlags.Default, args);
Type[] args = [typeof(string), typeof(string)];
MethodInfo? foo = objType.GetMethod("DoFoo", BindingFlags.Default, args);
However, I'm in a scenario where I don't know what one of the types is, because I get them from a collection of objects and through each object I get its type. When an object is null, it is not possible to determine its type, as they are all object?[].
Type[] args = [typeof(string), ???];
Type[] args = [typeof(string), ???];
I needed a way to specify a wildcard in a certain type position. Is there any way to do this?
3 Replies
cypherpotato
cypherpotato2mo ago
this snippet:
void Foo(string foo, string? n, object? b) { }
void Foo(string foo, string? n, string? b) { }

public void DoFoo()
{
Foo("aaa", null, null);
}
void Foo(string foo, string? n, object? b) { }
void Foo(string foo, string? n, string? b) { }

public void DoFoo()
{
Foo("aaa", null, null);
}
the compiler automatically select Foo(string, string?, string?) as the method for Foo, even if I've not specified any argument but null. How did the compiler made this decision?
Aaron
Aaron2mo ago
string is more specific than object, because string inherits from object therefore the string overload is better but no, you essentially have to use GetMethods and then replicate a piece of the compiler's overload resolution logic
cap5lut
cap5lut2mo ago
u could use Type.GetMethods(BindingFlags) to get an array of MethodInfo on which u can filter, and use its GetParameters() method to get an array of ParameterInfo to analyze it in a more complex fashion (sorry forgot to scroll down :s)