I am attempting to build a Dictionary
that looks like this:
var getValueFuncs = new Dictionary<TypeID, Func<string, object>>
{
{TypeID.BINARY, NotMine.GetBinaryValue},
{TypeID.BOOLEAN, NotMine.GetBooleanValue},
{TypeID.DATE, NotMine.GetDateTimeValue},
{TypeID.DOUBLE, NotMine.GetFloat64Value},
{TypeID.LONG, NotMine.GetInteger32Value},
{TypeID.STRING, NotMine.GetStringValue}
};
The various Func
s that I want to put into it all have different return types.
public interface INotMine : ICollection, ICloneable
{
byte[] GetBinaryValue(string propName);
bool? GetBooleanValue(string propName);
DateTime? GetDateTimeValue(string propName);
double? GetFloat64Value(string propName);
int? GetInteger32Value(string propName);
string GetStringValue(string propName);
}
Note that NotMine
is a separate class, that it inherits from INotMine
, and that I cannot change it.
The two lines to initialize the Dictionary
with the procedures that return byte[]
and string
compile with no trouble. The four lines for procedures that return nullable data types (i.e. bool?
, DateTime?
, double?
, and int?
) will not compile. They each report an error like this one:
bool? INotMine.GetBooleanValue(string propName)
'bool? INotMine.GetBooleanValue(string)' has the wrong return type
Expected a method with 'object GetBooleanValue(string)' signature
Given that everything inherits from object
, why will those lines not compile and go into my Dictionary
nicely?
EDIT: Before he deleted it, someone posted an answer that contained an elegant work-around that looked like this:
{TypeID.BINARY, s => NotMine.GetBinaryValue(s)}
I'm grateful for that, and I'll use that, but I'd still like to know why the original lines won't compile.
Nullable<T>
to anobject
, which requires a boxing conversion (this is essentially what the workaround provides). Yes, every type nominally inherits fromobject
, including value types, but they're still treated specially.