I have a basic filter class that stores a string
parameter name and a generic T
value. The filter has a method Write(writer As IWriter)
The problem is, when I call writer.Write(ParameterName, Value) and T is a string, it calls the overload for string/object, not string/string!
Yes, this is expected - or rather, it's behaving as specified. The compiler chooses the overload based on the compile-time types of the arguments, usually. There's no implicit conversion from T
to string
, so the only applicable candidate for the invocation of writer.Write(ParameterName, Value)
is the Write(string, object)
overload.
If you want it to perform overload resolution at execution time, you need to use dynamic typing. For example:
public void Write(FooWriter writer) {
// Force overload resolution at execution-time, with the execution-time type of
// Value.
dynamic d = Value;
writer.Write(ParameterName, d);
}
Note that this could still behave unexpectedly - if Value
is null, then it would be equivalent to calling writer.Write(ParameterName, null)
which would use the "better" function member - here writer.Write(string, string)
- even if the type of T
is object
!