All of these are wrong for the purpose described. If it is undetermined if the data is correct you cannot trust it, then it is normal if it is wrong, invalid, which cannot be converted, so the only correct way to perform this operation is to try to convert and check whether the operation worked or not. Although it works in other ways, the most correct and efficient is the use of TryParse()
. Its use has already been answered in Differences between Parse vs Tryparse. See also because the use of Convert
is inappropriate. See also about the use of cast.
This goes for any type of conversion, not just for float. If you have a text and it is not guaranteed of what is written there need to do the process of Parsing to understand what is in the text, validate and then make the conversion. The Parse()
can be used when you are sure that the data is valid and will certainly be converted correctly, which is not the case in data entry by the console.
The guy float
has his TryParse()
, use it and you don’t even have to worry about it.
Nor is there a Convert.ToInt()
because the guy from framework flame int
(there is a Convert.ToInt32()
which is the name . NET uses), as well as the float
for C# is the same as the Single
for .NET. NET needs to work with the universal name of the type, so there is a Convert.ToSingle()
. The name float
it’s just one alias that C# uses, not the official name of the type that can be used for other languages.
But every time you meet one string the ideal is not to convert and yes parse. Even if you have a situation that ensures that the data is a valid floating type number the most correct is the use of the float.Parse()
. A case that could be useful using the Convert.ToSingle()
is if the value can be null, but this pattern should be avoided, at least you should check first. If language were created today this method would not even exist.
But there are several other questions showing the correct use (this is one of the most poorly used things by programmers).
-
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero