20 Replies
I realize whats wrong Im just not certain on how I fix it
if i enter a letter this line obviously cant convert it
double isales = Convert.ToDouble(sales);
How do i fix
$tryparse
The TryParse pattern is considered best practice of parsing data from a string:
- a TryParse method returns
true
or false
to inform you if it succeeded or not, so you can use it directly in a condition,
- since C# 7 you can declare a variable that will be used as an out
argument inline in an argument list,
- it forces you to check if the out
argument contains valid data afterwards,
Avoid: Convert.ToInt32 — it's a bad choice for parsing an int
. It exists only for backwards compatibility reasons and should be considered last resort. (Note: Convert does contain useful conversion methods: To/FromBase64String
, To/FromHexString
, ToString(X value, int toBase)
, ToX(string? value, int fromBase)
)
Avoid: int.Parse — you have to use a try
/catch
statement to handle invalid input, which is a less clean solution.
Use int.TryParse https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__ Int32.TryParse Method (System)
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.
This method was made for this explicit reason
It checks if your string can be converted into a given numeric type, and if so, converts it
im finding it a bit confusing to understand, where would i put this in my code and what would i need to change
You'd use it instead of your convert
Ahhh I see ive got it in now and its working thank you
How would I return overtime so I can use it down there
@Angius
result
is your parsed numberyeah but how do i still get it down to use there because changing overtime to result it still cant reach it
You're trying to use the variable in the outermost scope
So you need to declare it in the outermost scope
And instead of
out var result
in your tryparse, you can then use out thatOuterVariable
so do i put int overtimetotal = (overtime * 15);
inside of the parse one
Try and see
Well, that's not how you do it, then
$scopes
thing a
is available in scope A
and scope B
thing b
is available only in scope B
im confused so where abouts do i put it
You're trying to use the
overtimetotal
variable in the outermost scope
So you need to declare it in the outermost scope
That's the tl;drohhhhhhhh isee now thank you so much
taking me a while to wrap my head around it lol