I have this (as well as Subtract, Divide, etc. I chose not to go w/ static operators),
public interface Add<T, G>
{
T Add(G b);
}
T, G are guaranteed to be data classes (not yet in code)
All data classes implement SType interface and SType is what gets passed around.
So the SType interface does not contain any information about whether or not a data class implements Add<T,G> (and data classes can implement multiple Add<T,G> interfaces).
So the overloaded (nothing known, output known, input known, both known) function I am trying to write takes two data classes and either adds them and returns a data class OR throws a custom exception.
Now when T and G are known,
I just use the as keyword to cast the SType interface to Add<T,G> interface and if it returns null, I throw an exception.
var addable = _this as Add<X, G>;
Now what if I don't know T or G (don't know what goes in and goes out)? Or just know T? Or just know G?
The easy solution is to use dynamic in a try catch. Like,
((dynamic)_this).Add(_other)
Questions,
1. If generic arguments are not known (or partially known), in terms of performance, is better to check that there is ANY implementation of Add interface before using dynamic to attempt to invoke it?
Question
+Red King Subscriber²
I have this (as well as Subtract, Divide, etc. I chose not to go w/ static operators),
T, G are guaranteed to be data classes (not yet in code)
All data classes implement SType interface and SType is what gets passed around.
So the SType interface does not contain any information about whether or not a data class implements Add<T,G> (and data classes can implement multiple Add<T,G> interfaces).
So the overloaded (nothing known, output known, input known, both known) function I am trying to write takes two data classes and either adds them and returns a data class OR throws a custom exception.
Now when T and G are known,
I just use the as keyword to cast the SType interface to Add<T,G> interface and if it returns null, I throw an exception.
Now what if I don't know T or G (don't know what goes in and goes out)? Or just know T? Or just know G?
The easy solution is to use dynamic in a try catch. Like,
Questions,
1. If generic arguments are not known (or partially known), in terms of performance, is better to check that there is ANY implementation of Add interface before using dynamic to attempt to invoke it?
Something like (not tested),
Link to comment
Share on other sites
3 answers to this question
Recommended Posts