C# using

devyumi·2025년 4월 11일

.NET

목록 보기
2/4

using


  • 자바의 try-with-resources처럼 사용한 자원을 해제하기 위해 사용하는 C# 키워드이다.

  • 자바의 try-with-resourcesAutoCloseable 인터페이스를 구현한 객체를 대상으로 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;
        }
    }
}

참고

profile
Web Back-end Junior Developer

1개의 댓글

comment-user-thumbnail
2025년 4월 15일

안뇽

답글 달기