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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With