3

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...

VJAI
  • 32,167
  • 23
  • 102
  • 164

5 Answers5

3

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.

Community
  • 1
  • 1
oopbase
  • 11,157
  • 12
  • 40
  • 59
3

Use tryparse :

string someString = "42";
int result;
if(int.TryParse(someString, out result))
{
    // It's ok
     Console.WriteLine("ok: " + result);
}
else
{
    // it's not ok
    Console.WriteLine("Shame on you");
}
Steve B
  • 36,818
  • 21
  • 101
  • 174
2

This is what you want;

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

    TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));

    try
    {   
        object val = converter.ConvertFromInvariantString(s);
        return true;
    }
    catch
    {
        return false;
    }
}
saj
  • 4,626
  • 2
  • 26
  • 25
1

Implementation example:

public static class StringExtensions
{
    public static bool Is<T>(this string s)
    {
        if (typeof(T) == typeof(int))
        {
            int tmp;
            return int.TryParse(s, out tmp);
        }

        if (typeof(T) == typeof(long))
        {
            long tmp;
            return long.TryParse(s, out tmp);
        }

        ...

        return false;
    }
}

Usage:

var test1 = "test".Is<int>();
var test2 = "1".Is<int>();
var test3 = "12.45".Is<int>();
var test4 = "45645564".Is<long>();

Also do note that you should take some other parameters as input for the method, such as IFormatProvider to let the user specify the culture to use.

ken2k
  • 48,145
  • 10
  • 116
  • 176
-2

I would use a try/catch

string a = "23";

try{

int b = a;

Console.WriteLine("valid integer");

}
catch
{
Console.WriteLine("invalid integer");
}
Oedum
  • 796
  • 2
  • 9
  • 28