I have the following method which attempts to parse a string into a type T when T provides a parse(string) method:
public static bool ParseToType<T>(string s, out T parsedValue) { if (typeof(T) == typeof(string)) { parsedValue = (T) s; //doesn't compile. return true; } if (!IsParseable(typeof(T))) { parsedValue = default(T); return false; } var meth = typeof(T).GetRuntimeMethod("Parse", new Type[] { typeof(String) }); try { parsedValue = (T)meth.Invoke(typeof(T), new String[] { s }); } catch ( Exception e) { parsedValue = default(T); return false; } return true; } However I need to deal with the special case when the type of T is also string. String doesnt provide a "parse" method, so I would just like to return the string supplied (s).
However I can't figure out how to cast s to T when T itself is string.
parsedValue = s;:)parsedValue = (T) (object) s;