How to use generic try-parse in C#

1 Answer

0 votes
using System;

public class CSharpMonoParserUtility
{
    // Define a delegate matching the exact signature of standard .NET TryParse methods
    public delegate bool TryParseHandler<T>(string input, out T result);

    /// <summary>
    /// Generic TryParse helper function optimized for Mono and .NET Standard 2.0.
    /// </summary>
    /// <typeparam name="T">The target type to parse into.</typeparam>
    /// <param name="input">The raw string input.</param>
    /// <param name="parser">The specific type's TryParse method delegate (e.g., int.TryParse).</param>
    /// <param name="result">The resulting parsed value if successful; otherwise, the default value.</param>
    /// <returns>True if parsing succeeded; otherwise, false.</returns>
    public static bool TryParseValue<T>(string input, TryParseHandler<T> parser, out T result)
    {
        result = default(T);

        // Guard clause: handle null, empty, or whitespace strings safely
        if (string.IsNullOrEmpty(input)) {
            return false;
        }

        // Invoke the passed parser delegate (e.g., int.TryParse)
        return parser(input.Trim(), out result);
    }

    public static void Main(string[] args)
    {
        // 1. Parsing an Integer in Mono
        if (TryParseValue<int>("2026", int.TryParse, out var intResult)) {
            Console.WriteLine($"Successfully parsed int: {intResult}");
        }

        // 2. Parsing a Boolean in Mono
        if (TryParseValue<bool>("true", bool.TryParse, out var boolResult)) {
            Console.WriteLine($"Successfully parsed bool: {boolResult}");
        }

        // 3. Handling invalid parsing gracefully
        if (!TryParseValue<int>("not-an-int", int.TryParse, out var invalidResult)) {
            Console.WriteLine("Failed to parse 'not-an-int' as expected, returning false safely.");
        }
    }
}


/*
run:

Successfully parsed int: 2026
Successfully parsed bool: True
Failed to parse 'not-an-int' as expected, returning false safely.

*/

 



answered Oct 28 by avibootz

Related questions

1 answer 305 views
1 answer 263 views
1 answer 284 views
1 answer 276 views
1 answer 295 views
...