Writing safe code in C#
C# can be considered a safe programming language by design. Unless you force it, there is no need for pointers, and memory release is, in most cases, managed by the garbage collector. Even so, some care should be taken so you can get better and safer results from your code. Let us have a look at some common practices to ensure safe code in C#.
try-catch
Exceptions in coding are so frequent that you should have a way to manage them whenever they happen. try-catch
statements are built to manage exceptions and they are important for keeping your code safe. There are a lot of cases where an application crashes and the reason for that is the lack of using try-catch
. The following code shows an example of the lack of usage of the try-catch
statement. It is worth mentioning that this is just an example for understanding the concept of an exception thrown without correct treatment. Consider using int.TryParse(textToConvert, out int result)
to handle cases where...