Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The answer is a big YES. You're trying to exploit the existence of the static T.TryParse(string, out T) function on the types you're converting to, and we can do that pretty easily with a little reflection. </p> <pre><code>public static T? ParseOrNull&lt;T&gt;(this string str) where T: struct, IConvertible { // find the TryParse method. var parseMethod = typeof(T).GetMethod("TryParse", // We want the public static one BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, // where the arguments are (string, out T) new[] { typeof(string), typeof(T).MakeByRefType() }, null); if (parseMethod == null) // You need to know this so you can parse manually throw new InvalidOperationException( string.Format("{0} doesn't have a TryParse(..) function!", typeof(T).FullName)); // create the parameter list for the function call var args = new object[] { str, default(T) }; // and then call the function. if ( (bool)parseMethod.Invoke(null, args)) return (T?)args[1]; // if it returned true // if it returned false return null; } </code></pre> <p>This is the original answer I provided, based on the idea that you need two different parse methods: One for value types and another for reference types.</p> <pre><code> public delegate bool ParseDelegate&lt;T&gt;(string s, out T result); public static T? ParseOrNull&lt;T&gt;(this string str, ParseDelegate&lt;T&gt; Parse) where T: struct { T result; if (!Parse(str, out result)) return null; return result; } public static T ParseOrNull&lt;T&gt;(this string str, ParseDelegate&lt;T&gt; Parse) where T : class { T result; if (!Parse(str, out result)) return null; return result; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload