Witam! W C# możemy napisać taki kod:
StreamReader reader = File.OpenText("file.txt");
try
{
// jakiś tam kod
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
Służy on do odczytania pliku i po zakończeniu tego odczytywania zwalnia zaalokowane zasoby. Można ten zapis skrócić za pomocą słówka using i kod po przekształceniu wygląda tak:
using (StreamReader reader = File.OpenText ("file.txt")
{
// jakiś kod
}
Czy da się skrócić kod z blokami try-catch-finally za pomocą using? Np: jakbym skrócił ten kod:
StreamReader reader = File.OpenText("file.txt");
try
{
// jakiś tam kod
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
Z góry dziękuję za pomoc!