1

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.

4
  • parsedValue = s; :) Commented Sep 16, 2017 at 22:21
  • 1
    Would be nice if that worked. Commented Sep 16, 2017 at 22:23
  • Oh, sorry my bad. Didn't notice it is generic type. Commented Sep 16, 2017 at 22:23
  • 3
    Maybe this will help: parsedValue = (T) (object) s; Commented Sep 16, 2017 at 22:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.