Try the following:
static class Ext
{
public static bool TryParse<T>(string s, out T value)
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
try
{
value = (T)converter.ConvertFromString(s);
return true;
}
catch
{
value = default(T);
return false;
}
}
public static bool ValidateLoopAttributes<T>(string i_value, T i_threshold)
where T : IComparable
{
T outval;
if (TryParse<T>(i_value, out outval))
return outval.CompareTo(i_threshold) >= 0;
else return false;
}
}
My answer uses Mark Gravell's answer taken from here .
With this you can do
bool b1 = Ext.ValidateLoopAttributes<int>("5", 4);
bool b2 = Ext.ValidateLoopAttributes<double>("5.4", 5.5d);
If you find this useful, you can also use the extension method.
public static bool ValidateLoopAttributes<T>(this string i_value, T i_threshold)
where T : IComparable { }
which allows you to use
bool b1 = "5".ValidateLoopAttributes<int>(4);
bool b2 = "5.4".ValidateLoopAttributes<double>(5.5d);
source
share