November 4, 2005 tools

Generics Q: Best way to convert a string to a T?

What’s the best way to implement the following semantic (feel free to change the signature)?

bool ConvertFromStringToT<T>(string in, ref T out) {…}

I’d like to be able to call it like so:

int x = 452;
double y = 77.7;

ConvertFromStringToT(“123”, ref x); // x is now 123
ConvertFromStringToT(“abc”, ref y); // y remains 77.7

I came up with a solution that relies more than I’d like on run-time behavior rather than compile-time behavior, which is why I’m asking.