How to use int.TryParse with nullable int?

Here's an option for a nullable int with TryParse

public int? TryParseNullable(string val)
{
    int outValue;
    return int.TryParse(val, out outValue) ? (int?)outValue : null;
}

You can't do this without using another variable, unfortunately - because the type of out arguments has to match the parameter exactly.

Like Daniel's code, but fixed in terms of the second argument, trimming, and avoiding comparisons with Boolean constants:

int tmp;
if (!int.TryParse(strValue.Trim(), out tmp))
{
    break;
}
intVal = tmp;

Could not prevent myself to produce a generic version. Usage below.

    public class NullableHelper
    {
        public delegate bool TryDelegate<T>(string s, out T result);

        public static bool TryParseNullable<T>(string s, out T? result, TryDelegate<T> tryDelegate) where T : struct
        {
            if (s == null)
            {
                result = null;
                return true;
            }

            T temp;
            bool success = tryDelegate(s, out temp);
            result = temp;
            return success;
        }

        public static T? ParseNullable<T>(string s, TryDelegate<T> tryDelegate) where T : struct
        {
            if (s == null)
            {
                return null;
            }

            T temp;
            return tryDelegate(s, out temp)
                       ? (T?)temp
                       : null;
        } 
    }


bool? answer = NullableHelper.ParseNullable<bool>(answerAsString, Boolean.TryParse);

You can create a helper method to parse a nullable value.

Example Usage:

int? intVal;
if( !NullableInt.TryParse( "42", out intVal ) )
{
    break;
}

Helper Method:

public static class NullableInt
{
    public static bool TryParse( string text, out int? outValue )
    {
        int parsedValue;
        bool success = int.TryParse( text, out parsedValue );
        outValue = success ? (int?)parsedValue : null;
        return success;
    }
}

Tags:

C#