The following code works fine:
public static void Main()
{
Foo<int>(5);
}
private static void Foo<T>(T x)
{
Bar((int)(object)x);
}
private static void Bar(int x)
{
}
However, my Bar method comes from a third-part library (Json.NET) that implements multiple overloads. Example:
private static void Bar(string x)
{
}
If I call Foo<int>(5)
, the Bar((int)(object)x)
conversion works fine, but calling Foo<string>("")
breaks at runtime (for obvious reasons, you can't convert string to int).
So, I would like to change the Bar((int)(object)x)
conversion to a generic Bar((T)(object)x)
conversion, but this gives the following compilation error:
cannot convert 'T' to 'int'
So, is it possible to convert object to T or the only solution is to using a switch-case convertion?