Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-17 00:00
관리 메뉴

nomad-programmer

[Programming/C#] using 문 본문

Programming/C#

[Programming/C#] using 문

scii 2020. 10. 1. 22:52
Python언어에서의 with문과 똑같은 역할을 한다고 생각하면 된다.

using문은 using 블록 내에서 예외가 발생하더라도 Dispose(또는 DisposeAsync)가 호출되도록 한다. try 블록 내부에 개체를 배치한 다음, finally 블록에서 Dispose(또는 DisposeAsync)를 호출해도 동일한 결과를 얻을 수 있다.
실제로 컴파일러는 이 방법으로 using 문을 변환한다.

C# 8.0 버전부터 using 문은 IAsyncDisposable 개체의 올바른 사용을 보장한다.

using문을 사용하지 않은 코드 예제

using System;
using System.IO;

namespace CSharpExample
{
    internal class MainApp
    {
        static int Main(string[] args)
        {
            string srcFile = @"c:/users/scii/desktop/aaa.txt";
            string dstFile = @"c:/users/scii/desktop/aaa2.txt";

            Stream openStream = new FileStream(srcFile, FileMode.Open);
            Stream createStream = new FileStream(dstFile, FileMode.Create);
            try
            {
                int size = 0;
                int totalSize = 0;
                byte[] buffer = new byte[1024];
                while ((size = openStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    createStream.Write(buffer, 0, size);
                    totalSize += size;
                }
                Console.WriteLine($"file size: {totalSize} bytes");
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }
            finally
            {
                openStream?.Close();
                createStream?.Close();
            }

            return 0;
        }
    }
}


/* 결과

file size: 61 bytes

*/

using문을 사용하는 코드 예제

using System;
using System.IO;

namespace CSharpExample
{
    internal class MainApp
    {
        static int Main(string[] args)
        {
            string srcFile = @"c:/users/scii/desktop/aaa.txt";
            string dstFile = @"c:/users/scii/desktop/aaa2.txt";

            using (Stream openStream = new FileStream(srcFile, FileMode.Open),
                createStream = new FileStream(dstFile, FileMode.Create))
            {
                int size = 0;
                int totalSize = 0;
                byte[] buffer = new byte[1024];
                while ((size = openStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    createStream.Write(buffer, 0, size);
                    totalSize += size;
                }
                Console.WriteLine($"file size: {totalSize} bytes");
            }

            return 0;
        }
    }
}


/* 결과

file size: 61 bytes

*/

C# 8.0 버전에서부터는 using문을 사용할 때 { } 블록을 사용하지 않아도 된다. 하지만 이 경우 위험할 수 있다. 따라서 위와 같이 using 문에서 개체를 인스턴스화하고 using 블록에서 범위를 제한하는 것이 좋다.

Comments