logo MSJO.kr

Pattern-based using with C# 8

2020-11-16
MsJ
 

C#에서 ‘using’ 키워드는 네임스페이스에서 유형을 가져오고 이에 대한 별칭을 만드는 지시문에 사용되는 것 외에 IDisposable 인터페이스에 사용하는 ‘using’이다1. 이것은 닷넷에 사용한 자원을 제거하도록 유도한다. 특히 C# 8버전에서는 ‘using’을 single line으로 구성할 수 있다2.

Class 생성(IDisposable)
public class AResource : IDisposable
{
    public void UseIt() => Console.WriteLine($"{nameof(UseIt)}");

    public void Dispose()
    {
        Console.WriteLine($"Dispose {nameof(AResource)}");
        GC.SuppressFinalize(this);
    }
}
전체 소스(Program.cs)
using System;

namespace ConsoleApp
{
    public class AResource : IDisposable
    {
        public void UseIt() => Console.WriteLine($"{nameof(UseIt)}");

        public void Dispose()
        {
            Console.WriteLine($"Dispose {nameof(AResource)}");
            GC.SuppressFinalize(this);
        }
    }

    internal class Program
    {
        private static void UsingStatement1() // Traditional
        {
            var ar = new AResource();
            try
            {
                ar.UseIt();
            }
            finally
            {
                ar.Dispose();
            }
        }

        private static void UsingStatement2() // New
        {
            using var ar = new AResource();
            ar.UseIt();
        }

        private static void UsingStatement3() // Multi
        {
            using var ar1 = new AResource();
            using var ar2 = new AResource();
            ar1.UseIt();
            ar2.UseIt();
        }

        private static void UsingStatement4() // Scope
        {
            {
                using var ar = new AResource();
                ar.UseIt();
            }
            Console.WriteLine("ar is already disposed");
        }

        public static AResource GetAResource() => new AResource();

        private static void UsingStatement5()
        {
            using var ar = GetAResource();
            ar.UseIt();
        }

        private static void Main()
        {
            UsingStatement1();
            Console.WriteLine("...UsingStatement1...End...\n");

            UsingStatement2();
            Console.WriteLine("...UsingStatement2...End...\n");

            UsingStatement3();
            Console.WriteLine("...UsingStatement3...End...\n");

            UsingStatement4();
            Console.WriteLine("...UsingStatement4...End...\n");

            UsingStatement5();
            Console.WriteLine("...UsingStatement5...End...");
        }
    }
}

/* 화면출력
UseIt
Dispose AResource
...UsingStatement1...End...

UseIt
Dispose AResource
...UsingStatement2...End...

UseIt
UseIt
Dispose AResource
Dispose AResource
...UsingStatement3...End...

UseIt
Dispose AResource
ar is already disposed
...UsingStatement4...End...

UseIt
Dispose AResource
...UsingStatement5...End...
*/
Reference
  1. CsharpChristiannagel, Using with C# 8
  2. Microsoft, “pattern-based using” and “using declarations”

Prεv  
Content
Search     RSS Feed     BY-NC-ND