Okay, so I realised after writing some overloaded methods that webmethods can’t be overloaded (by realised I mean VS threw a paddy and wouldn’t allow me to update the service references). I have tried to get around that like this:
public string DoPing<T>(T IP)
{
if (typeof(T) == typeof(string))
{
return DoPingString(IP);
}
if (typeof(T) == typeof(IPAddress))
{
return DoPingIP(IP);
}
throw new Exception("Programmer Error");
}
But I’m getting a cannot convert from T to string/Ipadress error when I call the respective (renamed) methods.
Can someone explain why it doesn’t work, and possibly either fix it or give me an alternate solution?
Thanks in advance.
Edit: Good point, generics are probably overkill (I tried for another solution and failed before trying this).
DoPingString(string String) and DoPingIP(IPAdress Address) are the signatures.
I will give the tick to the closest answer tomorrow. I solved the problem in a separate way.
You’re not using generics the way it was intended. The compiler has no idea what type T is, so it won’t just let you implicitly or explicitly cast to String or IPAddress.
Here’s a version that works:
However, since you’re using generics with no constraint, you gain no benefit from the generic implementation. Why not just take an object?
Of course, the simpler and easier approach would be to simply overload your function, i.e.: