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)
which will write the contents of the filter to an HTML page. The Write
method has two overloads, one which takes two strings and which takes a string and an object. This lets me auto-quote strings.
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! If I call the Write method on the writer
directly, it works as expected.
Here's an SSCE in C#. I tested this in both VB and C# and found the same problem
void Main() {
FooWriter writer = new FooWriter();
Filter<string> f = new Filter<string>() {ParameterName = "param", Value = "value"};
f.Write(writer); //Outputs wrote w/ object
writer.Write(f.ParameterName, f.Value); //Outputs wrote w/ string
}
class FooWriter {
public void Write(string name, object value) {
Console.WriteLine("wrote w/ object");
}
public void Write(string name, string value) {
Console.WriteLine("wrote w/ string");
}
}
class Filter<T> {
public string ParameterName {get; set;}
public T Value {get; set;}
public void Write(FooWriter writer) {
writer.Write(ParameterName, Value);
}
}
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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With