문제

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))
도움이 되었습니까?

해결책

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.

다른 팁

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);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top