using자바의 try-with-resources처럼 사용한 자원을 해제하기 위해 사용하는 C# 키워드이다.
자바의 try-with-resources가 AutoCloseable 인터페이스를 구현한 객체를 대상으로 close() 메서드를 호출하여 사용한 자원을 해제하는 것처럼, C# using 키워드 역시 IDisposable 인터페이스를 구현한 객체에 대해서 자동으로 Dispose() 메서드를 호출하여 자원을 해제한다.
JAVAC#자원 해제 키워드 try-with-resourcesusing인터페이스 AutoCloseableIDisposable메서드 close()Dispose()
아래 코드처럼 using 키워드를 사용하게 되면 sr.Close()나 sr.Dispose()를 호출할 필요가 없어진다.
참고로 StreamReader.Close()는 내부적으로 StreamReader.Dispose()를 호출하기 때문에 StreamReader.Dispose()를 사용하는 게 더 범용적이다.
string sPath = @"C:\example\" + DateTime.Now.ToString("yyyyMM") + @"\"; string sFileName = "example.DAT"; //디렉토리가 없을 경우 생성 if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } using(StreamReader sr = new StreamReader(sPath + sFileName, Encoding.UTF8)) { while (true) { string line = sr.ReadLine(); if (string.IsNullOrWhiteSpace(line) { break; } } }
참고
안뇽