"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can TryParse be used for generic type verification in C#?

Can TryParse be used for generic type verification in C#?

Posted on 2025-03-12
Browse:143

Can `TryParse` Be Used for Generic Type Validation in C#?

Extending Generic Type Validation with 'TryParse'

With the intent of verifying whether a given string adheres to a predefined type, an attempt is being made to develop a generic extension utilizing 'TryParse'. However, this effort has encountered a compilation obstacle as 'TryParse' remains unresolved.

The crux of this issue lies in the fact that 'TryParse' is not encapsulated within any recognizable interface. Hence, the question arises as to the feasibility of such an implementation.

One potential solution involves leveraging the TypeDescriptor class, a mechanism designed specifically for this purpose. By incorporating this class, a more robust approach can be adopted:

public static T Convert(this string input)
{
    try
    {
        var converter = TypeDescriptor.GetConverter(typeof(T));
        if (converter != null)
        {
            // Cast ConvertFromString(string text) : object to (T)
            return (T)converter.ConvertFromString(input);
        }
        return default(T);
    }
    catch (NotSupportedException)
    {
        return default(T);
    }
}

This updated approach boasts several advantages:

  • It eliminates the need for exceptions, fostering a more refined and efficient solution.
  • It retains the flexibility of accepting a specific type rather than relying on generics, allowing for greater versatility.

Ultimately, this revised solution effectively addresses the initial challenge, providing a means to ascertain the validity of a given input string against a predefined type.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3