Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method to check whether a string is valid integer, double, bool etc

Tags:

c#

I'm trying to create an extension method for string that says whether the string is a valid integer, double, bool or decimal. I'm not interested in switch..case and trying to use generics.

Extension method

public static bool Is<T>(this string s)
{
   ....
}

Usage

string s = "23";

if(s.Is<int>())
{
   Console.WriteLine("valid integer");
}

I couldn't able to succeed on implementing the extension method. I'm looking for some ideas/suggestions...

like image 669
VJAI Avatar asked Mar 07 '26 03:03

VJAI


1 Answers

This might work using the Cast<>() method:

    public static bool Is<T>(this string s)
    {
        bool success = true;
        try
        {
            s.Cast<T>();
        }
        catch(Exception)
        {
            success = false;
        }
        return success;
    }

EDIT

Obviously this doesn't work every time, so I found another working version here:

public static bool Is<T>(this string input)
{
    try
    {
        TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
    }
    catch
    {
        return false;
    }

    return true;
}

Taken from here.

like image 54
oopbase Avatar answered Mar 09 '26 17:03

oopbase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!