I’m trying to compile a project containing this method;
public void Send<T>(object o) where T : struct {
BinaryWriter bw = new BinaryWriter(stream);
bw.Write((T)o);
}
I inspired from this method (working);
public static T Cast<T>(object o) {
return (T)o;
}
BinaryWriter.Write function supports primitive types for parameters, so I thought I could use it like that. However, Visual Studio says “The best overloaded method match for ‘System.IO.BinaryWriter.Write(bool)’ has some invalid arguments“
I’m trying to avoid writing a long switch statement containing every primitive type and add a parameter to method for choosing the type. This is ugly and doesn’t seem right.
This is simple and elegant:
- Send< int>(123);
- Send< bool>(true);
But why isn’t it working? And what is the right way to do it?
Overload resolution is performed at compile time. So the compiler’s trying to find a method with a parameter which will be valid *whatever type
Tis, (within its constraints, which don’t help here). It can’t find such a method. Given that the only constraint is thatTmust be a struct, the only non-generic parameter type that would be valid would beobject(via boxing).If your aim was to use whichever overload was appropriate based on the execution-time type of the object, you’ll need to either use dynamic typing, like this:
… or fetch and execute the right overload with reflection (which is sort of what dynamic typing would do).