You haven't stated what the desired data type is: float
, Int64
(long
), or something else? Seeing as how myAge
is a float
in both snippets that suggests you want the user to be able to input a float
, so you should use a method that returns a float
.
You could certainly read a long
and store it in a float
, but I don't see any reason to do that. Why let your variable store a fractional part if you won't let the user actually input one? If you read a long
, store it in a long
. If you store a float
, call a method that reads a float
.
Note that you are comparing Convert.ToInt64()
to float.Parse()
, when it seems like you should be comparing...
Convert.ToInt64()
to Convert.ToSingle()
(float
being an alias for Single
), and...
float.Parse()
to long.Parse()
As others have mentioned, there are also TryParse()
versions of the Parse()
methods.
It all really comes down to personal preference. To me, parsing is the specific operation being performed, so I would choose a Parse()
(or TryParse()
) method. Some people might prefer the more general Convert.ToXXX()
methods since they have overloads for many more datatypes beyond just string
. In the end, Convert.ToInt64()
is internally calling Int64.Parse()
, anyways...
public static long ToInt64(string value) {
if (value == null)
return 0;
return Int64.Parse(value, CultureInfo.CurrentCulture);
}
...and is documented as such...
Using the ToInt64(String) method is equivalent to passing value
to the Int64.Parse(String) method.