Come on, let me explain.
using
This is when you will use an object and then discard it without storing information in memory.
using (StringBuilder sb = new StringBuilder()) {
sb.AppendLine("Olá, mundo!");
}
// o StringBuilder sb não existe mais na memória
It is only used with objects that implement IDisposeable
(disposable object). The using
block does not implement any condition or exception expressions.
try
is used when you will catch runtime errors within a block and will handle them.
int valor = 0;
try {
// tente fazer isso
valor = Convert.ToInt32("Isso não é um número");
} catch (Exception ex) {
// se der erro, faça isso com o erro:
Console.WriteLine("Não deu certo, pois " + ex.Message);
valor = 10;
} finally {
// no final, mesmo se der certo ou der erro,
valor *= 2;
}
At the end, value will be 20 , because inside the block it will give an error to convert that string to a number. In block catch
, value 10 is assigned to value , and in block finally
, the value is multiplied by two.
It is not recommended to use try
, but only when you will do something that needs user manipulation.
if
This is the classic conditional, it will only execute what is inside the block if the expression is true :
if(1 + 1 == 2) {
Console.WriteLine("Isso irá executar");
}
if(2 + 2 == 5) {
Console.WriteLine("Isso não irá executar");
}
Of course obvious and obvious values were used in the example above, but the if
block accepts variables and constants, as long as the final value is Boolean
.
Where to use it all?
You can combine the three blocks above, one inside the other, each one performing a function. You just have to understand what each one does.
Read the documentation .