Your user is entering a balance and is typing text, so how do you know the text can be represented by a number? C# will not let you convert a string to a double implicitely because there is no unique way to do that without make substantial assumptions about the string and implicit conversions should never throw an exception (Framework Design Guidelines), so it is best to not offer implicit conversion at all.
For example, since it is a balance, what if the user types "(100.25)" or "-100.25" or "-$100.25" or "-€100,25" or "negative one hundred and twenty-five cents" All of those are valid strings, so how would you convert them to a double?
The answer is that there is not one correct answer: you can map strings to double in any way that makes sense to you. You could, of course, write your own function of the form Func<String, double>
but there are functions provided by the .Net framework that implement the most common and intuitive conversions.
Others have posted double.Parse
and double.TryParse
so I want to add to make sure also to look into NumberStyles
and IFormatProvider
if necessary.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…