Sorry that I had to re-edit this question.
I need to dynamically parse two string values to the appropriate type and compare them, then return a bool result.
Example 1:
string lhs = “10”;
string rhs = “10”;
Compare.DoesEqual(lhs, rhs, typeof(int)); //true
Compare.DoesEqual(lhs, rhs, typeof(string)); //true
Example 2:
string lhs = “2.0”;
string rhs = “3.1”;
Compare.IsGreaterThan(lhs, rhs, typeof(int)); //false
Compare.IsGreaterThan(lhs, rhs, typeof(double)); //false
Compare.IsGreaterThan(lhs, rhs, typeof(string)); //invalid, always false
Currently I am doing like this (I think it's stupid to do it such way):
public partial class Comparer
{
public static bool DoesEqual(string lhs, string rhs, Type type)
{
if (type.Equals(typeof(int)))
{
try
{
return int.Parse(lhs) > int.Parse(rhs);
}
catch
{
return false;
}
}
if (type.Equals(typeof(double)))
{
try
{
return double.Parse(lhs) > double.Parse(rhs);
}
catch
{
return false;
}
}
return false;
}
}
And this:
public partial class Comparer
{
public static bool IsGreaterThan(string lhs, string rhs, Type type)
{
if (type.Equals(typeof(int)))
{
try
{
return int.Parse(lhs) == int.Parse(rhs);
}
catch
{
return false;
}
}
if (type.Equals(typeof(double)))
{
try
{
return double.Parse(lhs) == double.Parse(rhs);
}
catch
{
return false;
}
}
if (type.Equals(typeof(string)))
{
return lhs.Equals(rhs);
}
return false;
}
}
I am looking for better a better (more generic way) implementation (perhaps using Expression Tree?). I appreciate any suggestions. Thank you!