Replies: 6 comments
-
In my opinion this is a concern for reflection and not one for the language. Such syntax would immediately disable the type safety provided by the language and by generics. I do propose enhancements for reflection with generics, particular resolving generic methods: https://github.com/dotnet/corefx/issues/16567 If that proposal is adopted by the BCL then your code would resemble the following: public void Test(object param1)
{
var type = Param1.GetType();
var methodTest2Info = typeof(ClassOfTest2).GetGenericMethod(
nameof(ClassOfTest2.Test2), // name of the method
new Type[] { type } // the generic type arguments
);
methodTest2Info.Invoke(this, new object[] { param1 });
} Which is much more inline with how normal methods are resolved/invoked via reflection. |
Beta Was this translation helpful? Give feedback.
-
@HaloFour I really like that proposal, good work. However, wouldn't that be solved by something like InfoOf (see https://github.com/Fody/InfoOf as an example)? I know |
Beta Was this translation helpful? Give feedback.
-
As a side note, the |
Beta Was this translation helpful? Give feedback.
-
Note that another possible workaround is to use public void Test(object param1)
{
Test2((dynamic)param1);
}
public void Test2<T2>(T2 parameter)
{
// use parameter
} It has issues (the performance is going to be much worse than the generic version, though probably better than the reflection version), but it works and it's clear and short. |
Beta Was this translation helpful? Give feedback.
-
@svick good point, however, Test2 will then be called with dynamic as a generic argument, no? This has some unexpected side-effects when youre trying to do |
Beta Was this translation helpful? Give feedback.
-
@Mafii No, I don't know how you would use the same approach for |
Beta Was this translation helpful? Give feedback.
-
I would like to propose a way to dynamically invoke generic methods.
Currently this can be done without problems:
However, this is more complex (type of
object param1
is not known at compiletime):If I understood correctly, these two codensippets are equally executed in the clr (ignoring reflection).
However, the second snippet is way less useful and harder to read.
I would propose the following syntax:
Beta Was this translation helpful? Give feedback.
All reactions