Reputation: 4809
I have a service that validates the user input. So, in other layers I am just using the below statement to get the amount value assuming that it is already validated.
But while writing unit test cases, I realized this is failing. So, my question is do we need to ALWAYS try to parse the values whenever string values needs to be converted to actual types.
var amountValue = Convert.ToDecimal(string.Format("{0}.{1}", view.amount, view.fraction))
Upvotes: 0
Views: 62
Reputation: 494
Here is a convert method based on generics:
public static void Convert<T>(string text, out T value, CultureInfo culture) where T : IConvertible
{
if (typeof(T).IsEnum)
{
value = (T) Enum.Parse(typeof (T), text, true);
}
else
{
value = (T)System.Convert.ChangeType(text, typeof(T), culture);
}
}
Upvotes: 1
Reputation: 11607
You should parse strings because that's what you actually want to do.
A type conversion is something different than parsing.
Imagine a case where in the US you separate decimals with a dot .
and in EU you'd use a comma ,
. You can't really know how the locale separates decimals and whatnot (especially dates are crucial and should be PARSED no CONVERTED).
That said, the rule user input => parse is quite straight forward.
Upvotes: 1