Hold on, let me explain.
using
is for 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 block using
does not implement any condition expression or exceptions.
Try
is used when you will capture Runtime errors within a block and will manipulate 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;
}
In the end, value will be 20, because inside the block will give an error to convert that string to a number. In the block catch
, is assigned the value 10 for value, and on the block finally
, 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 perform 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 constant values were used in the above example, but the block if
accepts variables and constants, provided that the final value is Boolean
.
Where to use all this?
You can combine the three above blocks, one inside the other, each performing a function. You just need to understand what each one does.
Give a read on documentation.
The
using
serves one thing, theif
andelse
to another and thetry
,catch
andfinally
for a third thing. Technically, the question makes no sense. Semantically, when you say 'what you prefer?' automatically put the question - if it made sense - outside the scope of the site. Maybe we can help if you present a specific case in practice.– Diego Rafael Souza
using nothing more than a block for scope restriction and Disposis, all the rest are instructions that have nothing to do with this.
– Leandro Angelo
Using
creates a scope that is destroyed at the end, correct? But if I need to know whether a certain scope has been executed correctly or not, howusing
I would return if any exception were found?.try
trial,catch
reports andfinally
end. How to report exceptions in a blockusing
?– Giovani Rodrigo
Looking for links I found this and I think it’s duplicate: https://answall.com/q/165632/101
– Maniero