✅ try catch
hey for example (i know tryparse exists)
is there a way to seperate the try / catch in a way that if int1 is valid (but int2 and int3 not) that int1 is still set
4 Replies
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__ Do you mean wrapping each of them in a try / catch?
Not exactly sure what you mean.
yes, like wrapping each line in try catch
declare the ints outside of the try/catch and then inside the try block parse them in the order you want them to be set?
try/catch blocks aren't like transactions, any code that executes before an exception is thrown still modifies the program's state
if you want them entirely separate then you'd have to do individual try/catch blocks
but the real answer is to use TryParse