Is there any difference between these two code samples and if not, why does using
exist?
StreamWriter writer;
try {
writer = new StreamWrite
They're not entirely the same. The try
/finally
block does not protect against silly mistakes.
StreamWriter writer = new StreamWriter(...);
try {
...
writer = new StreamWriter(...);
...
} finally {
writer.Dispose();
}
Note that only the second writer gets disposed. In contrast,
using (StreamWriter writer = new StreamWriter(...)) {
...
writer = new StreamWriter(...);
...
}
will give a compile-time error.