Microsoft MVP성태의 닷넷 이야기
.NET Framework: 760. Microsoft Build 2018 - The future of C# 동영상 내용 정리 [링크 복사], [링크+제목 복사]
조회: 13833
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 11개 있습니다.)

Microsoft Build 2018 - The future of C# 동영상 내용 정리

이번 글은 다음 동영상을 보며 간략하게 정리한 것입니다.

Microsoft Build 2018 - The future of C# / Mads Torgersen, Dustin Campbell
; https://channel9.msdn.com/Events/Build/2018/BRK2155

C# 7.1 ~ 7.3의 주요 특징을 다음과 같이 정리하고 있습니다.

Safe, efficient code
    Avoid garbage collection
    Avoid copying
    Stay safe

More freedom
    Allow more things

Less code
    Say it shorter

자, 우선 C# 7.1에 추가된 리터럴에 밑줄을 추가하는 간단한 예제부터 시작합니다.

using System.Linq;
using static System.Console;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 0b1, 0b10, 0b100, 0b1000, 0b1_0000, 0b10_0000 };
            int result = SumOfSquares(numbers);

            WriteLine(result);
        }

        private static int SumOfSquares(int[] numbers)
        {
            return numbers.Select(i => i * i).Sum();
        }
    }
}

C# 7.2부터 구분자(0b, 0x) 다음에도 "_" 밑줄 문자가 오는 것을 허용합니다.

// C# 7.1까지는 "Error CS8302 Feature 'leading digit separator' is not available in C# 7.1" 오류 발생
int[] numbers = { 0b_1 };

그리곤, 위의 코드에서 SumOfSquares를 비동기 처리로 바꿉니다.

using System.Linq;
using System.Threading.Tasks;
using static System.Console;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            int[] numbers = { 0b1, 0b10, 0b100, 0b1000, 0b1_0000, 0b10_0000 };
            int result = await SumOfSquaresAsync(numbers);

            WriteLine(result);
        }

        private static async Task<int> SumOfSquaresAsync(int[] numbers)
        {
            return numbers.Select(i => i * i).Sum();
        }
    }
}

async에 취소 기능을 넣으면서 기본값 예약어를 넣을 수 있습니다.

private static async Task<int> SumOfSquaresAsync(int[] numbers, CancellationToken ct = default)
{
    return numbers.Select(i => i * i).Sum();
}

물론, 위의 코드는 async/await을 적용하긴 했지만 내부적으로 비동기 처리가 되는 것은 아닙니다. 실제로 비동기 처리를 하려면 다른 비동기 메서드를 호출하거나, 아니면 스스로 스레드 생성을 하면 됩니다. 이를 위해 Local Function을 이용한 비동기 처리를 다음과 같이 할 수 있습니다.

using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static System.Console;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            int[] numbers = { 0b1, 0b10, 0b100, 0b1000, 0b1_0000, 0b10_0000 };
            int result = await SumOfSquaresAsync(numbers);

            WriteLine(result);
        }

        private static async Task<int> SumOfSquaresAsync(int[] numbers, CancellationToken ct = default /* C# 7.1부터 가능 */)
        {
            return await Task.Run(Compute, ct); // C# 7.3부터 컴파일 가능

            int Compute() => numbers.Select(i => i * i).Sum(); // C# 7.0의 Local Function
        }
    }
}

게다가 위의 코드는 C# 7.2까지는 Run 메서드가 정의한 제네릭 버전과의 모호함으로 인해 다음과 같이 오류가 발생했지만 이젠 그것도 수정되었습니다.

error CS0121: The call is ambiguous between the following methods or properties: 'Task.Run<TResult>(Func<TResult>)' and 'Task.Run(Func<Task>)'

Named Arguments가 추가된 C# 7.2부터는 다음과 같이 명시적인 인자 지정도 가능합니다.

private static async Task<int> SumOfSquaresAsync(int[] numbers, CancellationToken ct = default)
{
    return await Task.Run(function: Compute, ct);
    int Compute() => numbers.Select(i => i * i).Sum();
}




제네릭 관련해서는 where 제약에 Delegate, Enum과 unmanaged가 추가되었습니다.

void M<D, E>(D d, E e) where D : Delegate
                        where E: Enum
{
}

또한 tuple의 Equals(==) 비교도 지원하는데 아래는 이를 모두 반영한 예제 코드입니다.

unsafe void M<D, E, T>(D d, E e, T* pointer) where D : Delegate
                        where E: Enum
                        where T: unmanaged
{
    var tuple = (d, Math.PI);
    bool result = tuple == (null, 42);
}




이제 ref 예약어를 설명하기 위해 간단한 예제 코드를 만들고,

using static System.Console;

namespace RefSample
{
    static class Program
    {
        static int OrMaybe(int x, int y)
        {
            x++; y--;
            return x;
        }

        static void Main(string[] args)
        {
            int a = 1, b = 10;
            int c = OrMaybe(a, b);

            WriteLine($"a = {a}, b = {b}, c = {c}"); // a = 1, b = 10, c = 2
        }
    }
}

다음은 ref 예약어로 참조를 받도록 변경한 것입니다.

using static System.Console;

namespace RefSample
{
    static class Program
    {
        static int OrMaybe(ref int x, ref int y)
        {
            x++; y--;
            return x;
        }

        static void Main(string[] args)
        {
            int a = 1, b = 10;
            int c = OrMaybe(ref a, ref b);

            WriteLine($"a = {a}, b = {b}, c = {c}"); // a = 2, a = 9, a = 2
        }
    }
}

그리고 C# 7.2부터 ref 인자에 대한 확장 메서드도 가능하게 됩니다.

using static System.Console;

namespace RefSample
{
    static class Program
    {
        static int OrMaybe(this ref int x, ref int y)
        {
            x++; y--;
            return x;
        }

        static void Main(string[] args)
        {
            int a = 1, b = 10;
            int c = a.OrMaybe(ref b);

            WriteLine($"a = {a}, b = {b}, c = {c}");
        }
    }
}

ref + readonly 기능의 in 매개 변수 사용도 해보겠습니다.

using static System.Console;

namespace RefSample
{
    static class Program
    {
        static int OrMaybe(this ref int x, in int y)
        {
            x++; // y--;
            return x;
        }

        static void Main(string[] args)
        {
            int a = 1, b = 10;
            int c = a.OrMaybe(/* in */ b); // in을 명시해도 좋고, 하지 않아도 상관없음.

            WriteLine($"a = {a}, b = {b}, c = {c}");
        }
    }
}

참고로 in을 명시해야만 하는 경우도 있습니다. 가령 다음과 같이 2개의 메서드가 있으면,

void Test(int a);
void Test(in int a);

호출 측에서 in을 명시하면 Test(in int a) 메서드가 호출되고 그렇지 않으면 Test(int a) 메서드가 호출됩니다.

이어서, ref 반환이 되도록 예제를 바꿔봅니다.

using static System.Console;

namespace RefSample
{
    static class Program
    {
        static ref int OrMaybe(this ref int x, in int y)
        {
            x++; // y--;
            return ref x;
        }

        static void Main(string[] args)
        {
            int a = 1, b = 10;
            ref int c = ref a.OrMaybe(/* in */ b);
            c = 1000;

            WriteLine($"a = {a}, b = {b}, c = {c}"); // a = 1000, b = 10, c = 1000
        }
    }
}

ref 반환값 역시 readonly를 부여할 수 있습니다.

using static System.Console;

namespace RefSample
{
    static class Program
    {
        static ref readonly int OrMaybe(this in int x, in int y)
        {
            // x++; // y--;
            return ref x;
        }

        static void Main(string[] args)
        {
            int a = 1, b = 10;
            ref readonly int c = ref a.OrMaybe(/* in */ b);
            // c = 1000;
            a = 1000;

            WriteLine($"a = {a}, b = {b}, c = {c}"); // a = 1000, b = 10, c = 1000
        }
    }
}

이미 한번 가리킨 적이 있는 ref 변수에 대해 다른 변수를 가리키게 만드는 것도 C# 7.3부터 가능해졌습니다.

static void Main(string[] args)
{
    int a = 1, b = 10;
    ref readonly int c = ref a.OrMaybe(/* in */ b);
    // c = 1000;
    a = 1000;

    int d = 0;
    c = ref d; // C# 7.2이전에는 컴파일 에러 - error CS8320: Feature 'ref reassignment' is not available in C# 7.2. Please use language version 7.3 or greater.

    WriteLine($"a = {a}, b = {b}, c = {c}"); // a = 1000, b = 10, c = 0
}

참조 변수가 대상의 scope보다 넓은 경우 당연히 오류가 발생합니다.

static void Main(string[] args)
{
    int a = 1, b = 10;
    ref readonly int c = ref a.OrMaybe(/* in */ b);
    // c = 1000;
    a = 1000;

    {
        int d = 0;
        c = ref d; // 컴파일 에러 - error CS8374: Cannot ref-assign 'd' to 'c' because 'd' has a narrower escape scope than 'c'.
    }

    WriteLine($"a = {a}, b = {b}, c = {c}");
}




계속해서 이번에는 Span 타입을 위한 예제를 보겠습니다.

using System;
using static System.Console;

namespace SpanSample
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];
            for (int i = 0; i < 10; i++) array[i] = i;
            foreach (int v in array) WriteLine(v); // 0 ~ 9 출력
        }
    }
}

위의 코드에서 배열의 View를 Span으로 생성할 수 있습니다.

using System;
using static System.Console;

namespace SpanSample
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];

            for (int i = 0; i < 10; i++) array[i] = i;
            Span<int> span = array.AsSpan();

            foreach (int v in span) WriteLine(v); // 0 ~ 9 출력
        }
    }
}

당연히 참조 View이기 때문에 다음과 같이 원본의 데이터를 변경하는 것도 가능하고,

static void Main(string[] args)
{
    int[] array = new int[10];

    Span<int> span = array.AsSpan();
    for (int i = 0; i < 10; i++) span[i] = i;

    foreach (int v in array) WriteLine(v); // 0 ~ 9 출력
}

부분 참조 View를 생성하는 것도 가능합니다.

static void Main(string[] args)
{
    int[] array = new int[10];
    for (int i = 0; i < 10; i++) array[i] = i;

    Span<int> span = array.AsSpan();
    Span<int> slice = span.Slice(3, 5); // index 3부터 시작해 5개의 요소에 대한 View

    foreach (int v in slice) WriteLine(v);  // 3 ~ 7 출력
}

또한 readonly Span 타입도 제공합니다.

static void Main(string[] args)
{
    int[] array = new int[10];

    ReadOnlySpan<int> span = array.AsSpan();
    ReadOnlySpan<int> slice = span.Slice(3, 5);

    for (int i = 0; i < 10; i++) array[i] = i;

    foreach (int v in slice) WriteLine(v); 
}

게다가 스택에 할당된 stackalloc 배열에 대해서도 일관성 있는 View를 제공합니다.

using System;
using static System.Console;

namespace SpanSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Span<int> span = stackalloc int[10];
            Span<int> slice = span.Slice(3, 5);

            for (int i = 0; i < 10; i++) span[i] = i;

            foreach (int v in slice) WriteLine(v); 
        }
    }
}




이후에는 C# 8.0의 Nullable reference type에 대해 설명합니다. (따라서 현재의 Visual Studio 2017로는 빌드가 안됩니다.) 설명을 위한 시작 예제는 다음과 같고,

using static System.Console;

namespace NullableSample
{
    class Program
    {
        static void Main(string[] args)
        {
            var miguel = new Person("Miguel", "de Icaza");
            int length = GetLengthOfMiddleName(miguel);
            WriteLine(length);
        }

        static int GetLengthOfMiddleName(Person p)
        {
            return p.MiddleName.Length;
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }

        public Person(string firstName, string middleName, string lastName)
        {
            FirstName = firstName;
            MiddleName = middleName;
            LastName = lastName;
        }
    }
}

위의 코드는 C# 8.0부터 public Person(string firstName, string lastName) 생성자에서 다음과 같은 경고가 발생하게 됩니다.

warning CS8618: Non-nullable property 'MiddleName' is uninitialized.

심지어 이렇게 null로 초기화해도 경고는 없어지지 않습니다.

public Person(string firstName, string lastName)
{
    FirstName = firstName;
    MiddleName = default; /* MiddleName = null; */
    LastName = lastName;
}

경고가 발생하지 않게 하려면 명시적으로 nullable임을 표시해야 합니다.

public class Person
{
    public string FirstName { get; set; }
    public string? MiddleName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        MiddleName = null;
        LastName = lastName;
    }

    public Person(string firstName, string middleName, string lastName)
    {
        FirstName = firstName;
        MiddleName = middleName;
        LastName = lastName;
    }
}

그런 경우 다시 MiddleName을 사용하는 코드에서 컴파일 경고가 발생할 수 있습니다.

static int GetLengthOfMiddleName(Person p)
{
    // 컴파일 경고: Possible dereference of a null reference.
    return p.MiddleName.Length;
}

상식적으로 nullable이기 때문에 언제든 null 값 상태일 수 있으므로 저렇게 작성하면 null 참조 예외가 발생할 가능성을 C# 컴파일러가 미리 막아주는 것입니다. 따라서 이 경고를 없애려면 반드시 null 체크 코드를 추가해야 합니다.

static int GetLengthOfMiddleName(Person p)
{
    if (p.MiddleName == null)
    {
        return 0;
    }

    return p.MiddleName.Length; // 컴파일 경고 사라짐
}

/* 또는 이런 식으로든지. */
/*
static int GetLengthOfMiddleName(Person p)
{
    var middleName = p.MiddleName;

    if (middleName == null)
    {
        middleName = "";
    }

    return middleName.Length;
}
*/

물론 이렇게 만들면 기존 코드들에서 상당히 많은 경고가 발생할 수 있기 때문에 8600 경고에 대해 .csproj 파일에서 끄는 것이 가능합니다.

<NoWarn>8600;$(NoWarn)</NoWarn>




이제 C# 8.0의 패턴 매칭으로 들어갑니다. ^^ 시작 예제는 이렇고,

using System;

namespace GoodiesSample
{
    class Program
    {
        static void Main(string[] args)
        {
            var professor = new Professor("Mads", "Torgersen", "Computer Sceience");

            var people = new[]
            {
                professor,
                new Student("Phillip", "Carter", professor),
                new Person("Dustin", "Campbell")
            };

            foreach (var p in people)
            {
                Console.WriteLine(M(p));
            }
        }

        static string M(Person person)
        {
            switch (person)
            {
                case Professor p:
                    return $"Dr. {p.LastName}, Professor of {p.Subject}";

                case Student s:
                    return $"{s.FirstName}, Student of Dr. {s.Advisor.LastName}";

                case Person p when p.LastName == "Campbell":
                    return $"Please, enroll, {p.FirstName}";

                case _: // C# 7.3 이전에는 컴파일 오류 - error CS0103: The name '_' does not exist in the current context value
                    return "Come back next year!";
            }
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
            => (FirstName, LastName) = (firstName, lastName);

        public void Deconstruct(out string firstName, out string lastName)
            => (firstName, lastName) = (FirstName, LastName);
    }

    public class Professor : Person
    {
        public string Subject { get; set; }

        public Professor(string firstName, string lastName, string subject)
            : base(firstName, lastName) => Subject = subject;

        public void Deconstruct(out string firstName, out string lastName, out string subject)
            => (firstName, lastName, subject) = (FirstName, LastName, Subject);
    }

    public class Student : Person
    {
        public Professor Advisor { get; set; }

        public Student(string firstName, string lastName, Professor advisor)
            : base(firstName, lastName) => Advisor = advisor;

        public void Deconstruct(out string firstName, out string lastName, out Professor advisor)
            => (firstName, lastName, advisor) = (FirstName, LastName, Advisor);
    }
}

위의 코드에서 기다란 switch 구문의 M 메서드를 아래와 같은 약식으로 바꾸는 구문을 지원한다고 합니다.

static string M(Person person)
{
    return person switch
    {
        Professor p => $"Dr. {p.LastName}, Professor of {p.Subject}", 
        Student s => $"{s.FirstName}, Student of Dr. {s.Advisor.LastName}",
        Person p when p.LastName == "Campbell" => $"Please, enroll, {p.FirstName}",
        _ => "Come back next year!"
    }
}

또한 마지막 Person 객체에 대한 패턴 코드를 아래와 같이 간단하게 바꿀 수도 있고,

static string M(Person person)
{
    return person switch
    {
        Professor p => $"Dr. {p.LastName}, Professor of {p.Subject}", 
        Student s => $"{s.FirstName}, Student of Dr. {s.Advisor.LastName}",
        Person { LastName == "Campbell" } p => $"Please, enroll, {p.FirstName}",
        _ => "Come back next year!"
    };
}

이름 변경도 가능합니다.

static string M(Person person)
{
    return person switch
    {
        Professor p => $"Dr. {p.LastName}, Professor of {p.Subject}", 
        Student s => $"{s.FirstName}, Student of Dr. {s.Advisor.LastName}",
        Person { LastName == "Campbell", FirstName: var fn } => $"Please, enroll, {fn}",
        _ => "Come back next year!"
    };
}

Person은 너무나 확정적이어서 생략도 가능하며,

static string M(Person person)
{
    return person switch
    {
        Professor p => $"Dr. {p.LastName}, Professor of {p.Subject}", 
        Student s => $"{s.FirstName}, Student of Dr. {s.Advisor.LastName}",
        { LastName == "Campbell", FirstName: var fn } => $"Please, enroll, {fn}",
        _ => "Come back next year!"
    };
}

개별 조건의 타입에 대한 Deconstruct가 있다면 이렇게도 가능합니다.

static string M(Person person)
{
    return person switch
    {
        Professor (_, var ln, var s) => $"Dr. {ln}, Professor of {s}", 
        Student (var fn, _, var a) => $"{fn}, Student of Dr. {a.LastName}",
        { LastName == "Campbell", FirstName: var fn } => $"Please, enroll, {fn}",
        _ => "Come back next year!"
    };
}

심지어 중첩 Deconstruct도 배려했습니다.

static string M(Person person)
{
    return person switch
    {
        Professor (_, var ln, var s) => $"Dr. {ln}, Professor of {s}", 
        Student (var fn, _, var (_, ln, _)) => $"{fn}, Student of Dr. {ln}",
        { LastName == "Campbell", FirstName: var fn } => $"Please, enroll, {fn}",
        _ => "Come back next year!"
    };
}




그다음 C# 8.0의 기능 설명을 위한 예제로부터,

using System;
using static System.Console;

namespace RangesSample
{
    class Program
    {
        static void PrintBanner(string text)
        {
            if (text?.Length >= 2 && text[0] == '"' && text[text.Length - 1] == '"')
            {
                text = text.Substring(1, text.Length - 1);
            }

            WriteLine(text);
        }

        static void PrintNumbers()
        {
            int[] array = new int[10];
            for (int i = 0; i < array.Length; i++) array[i] = i;

            foreach (var v in array) WriteLine(v);
        }

        static void Main(string[] args)
        {
            PrintBanner('"' + "The Mads and Dustin Show" + '"');
            // PrintNumbers();
        }
    }
}

(파이썬으로부터 베껴 온 ^^) System.Index 타입을 이용한 문자열 범위 지정을 다음과 같이 도입할 수 있습니다.

static void PrintBanner(string text)
{
    if (text?.Length >= 2 && text[0] == '"' && text[^1] == '"')
    {
        text = text.Substring(1, text.Length - 1);
    }

    WriteLine(text);
}

또는 이렇게도 가능한데,

static void PrintBanner(string text)
{
    var last = ^1;

    if (text?.Length >= 2 && text[0] == '"' && text[last] == '"')
    {
        text = text.Substring(1, text.Length - 1);
    }

    WriteLine(text);
}

위의 코드는 실행하면 text.Substring에서 잘못된 결과를 반환합니다. 목적에 맞게 수정하려면 다음과 같이 해야 하지만,

text = text.Substring(1, text.Length - 2);

위와 같이 -1, -2 등의 지정이 꽤나 마음에 들지 않는 코딩 방식이라면서 이제는 Substring 역시 System.Index 타입을 지원하는 버전을 추가할 것이므로 다음과 같이 좀 더 쉽게 지정할 수 있다고 합니다.

static void PrintBanner(string text)
{
    var last = ^1;

    if (text?.Length >= 2 && text[0] == '"' && text[last] == '"')
    {
        text = text.Substring(1..^1);
    }

    WriteLine(text);
}

게다가 string의 indexer에도 추가할 것이므로 다음과 같이 파이썬과 매우 유사한 코드로의 변경을 지원합니다.

static void PrintBanner(string text)
{
    var last = ^1;

    if (text?.Length >= 2 && text[0] == '"' && text[last] == '"')
    {
        text = text[1..^1];
    }

    WriteLine(text);
}

string뿐만 아니라 배열 역시 지원을 하므로 다음과 같은 표현이 가능합니다.

static void PrintNumbers()
{
    int[] array = new int[10];
    Span<int> slice = array[4..8];
    for (int i = 0; i < array.Length; i++) array[i] = i;

    foreach (var v in slice) WriteLine(v); // 4 ~ 7 출력
}

물론, ^0이나 마지막 인덱스를 생략할 수도 있고,

static void PrintNumbers()
{
    int[] array = new int[10];

    // ^0으로 지정하는 것도 가능하고,
    // Span<int> slice = array[4..^0];

    // 없이 지정하는 것도 가능
    Span<int> slice = array[4..];

    for (int i = 0; i < array.Length; i++) array[i] = i;

    foreach (var v in slice) WriteLine(v); // 4 ~ 9 출력
}

마찬가지로 시작 인덱스 측에도 생략이 가능합니다.

static void PrintNumbers()
{
    int[] array = new int[10];

    Span<int> slice = array[..8];

    for (int i = 0; i < array.Length; i++) array[i] = i;

    foreach (var v in slice) WriteLine(v); // 0 ~ 7 출력
}

당연히 앞/뒤 생략도 가능하고!

static void PrintNumbers()
{
    int[] array = new int[10];

    Span<int> slice = array[..];

    for (int i = 0; i < array.Length; i++) array[i] = i;

    foreach (var v in slice) WriteLine(v); // 0 ~ 7 출력
}




C# 8.0부터 비동기 Dispose가 허용돼 using 구문에도 await 사용이 가능하다고 합니다.

using System;
using System.IO;
using System.Threading.Tasks;
using static System.Console;

class LongRunningDisposable : IAsyncDisposable
{
    public async Task DisposeAsync()
    {
        WriteLine();
        WriteLine($"{nameof(DisposeAsync)}: Oh dear! This might take awhile!");
        await Task.Delay(2000);
        WriteLine($"{nameof(DisposeAsync)}: Whew! Done!");
        WriteLine();
    }
}

class Program
{
    static async Task Main(string [] args)
    {
        using await (new LongRunningDisposable())
        {
            WriteLine($"{nameof(Main)}: Using a resource with a long running {nameof(LongRunningDisposable)}");
        }

        WriteLine($"{nameof(Main)}: Finished with resource.");
        WriteLine();
    }
}

또한 foreach 문에서도 await이 가능하도록 바뀐다고!

using System.IO;
using System.Linq;
using System.Threading.Tasks;
using static System.Console;

class Program
{
    static (Stream stream, long checkSum) CreateStream()
    {
        var checksum = 0L;

        var bytes = new byte[20000];
        
        for (int i = 0; i < bytes.Length; i ++)
        {
            var value = (byte)(i % byte.MaxValue);
            bytes[i] = value;

            unchecked { checksum += value; }
        }

        var stream = new MemoryStream(bytes);
        return (stream, checksum);
    }

    static async Task Main(string[] args)
    {
        var (stream, checksum) = CreateStream();

        var c = 0L;

        foreach await (var b in stream.AsEnumerable())
        {
            unchecked { c += b; }
        }
           
        if (c == checksum)
        {
            WriteLine("Checksums match!");
        }
    }
}




위에까지의 C# 8.0 구문은 현재 내부 C# 컴파일러 버전에서 구현된 것인 반면 아래의 구문들은 프로토타입 중이라고 합니다.

먼저 자바에서 가능한 "Default Interface Members"인데,

interface ILogger
{
    void Log(LogLevel level, string message);
    void Log(Exception ex) => Log(LogLevel.Error, ex.ToString());
}

보는 바와 같이 인터페이스에 메서드를 정의할 수 있습니다. 다음의 문서를 보면, 다른 언어들에서 볼 수 있는 문법이므로 이에 보조를 맞추기 위한 정도로 채택된 것 같습니다.

A Tour of Default Interface Methods for C# ("traits")
; https://github.com/dotnet/csharplang/issues/288

마지막으로 설명한 것이 Record 지원인데 다음과 같이 간단한 코드로,

class Person(string First, string Last);

C# 컴파일러는 자동으로 아래와 같은 식의 코드를 생성해 준다고 합니다.

class Person : IEquatable<Person>
{
    public string First { get; }
    public string Last { get; }

    public Person(string First, string Last) => (this.First, this.Last) = (First, Last);
    public void Deconstruct(out string First, out string Last) => (First, Last) = (this.First, this.Last);
    public bool Equals(Person other) => other != null && First == other.First && Last == other.Last;

    public override bool Equals(object obj) => obj is Person other ? Equals(other) : false;
    public override int GetHashCode() => GreatHashFunction(First, Last);
    // ...
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/15/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2018-06-07 11시57분
[spowner] 깔끔한 정리 감사합니다. c# 8.0의 문자열 범위 지정 참 마음에 드는 확장이네요.
[guest]

1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241557닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241563닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241643닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241620닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241635닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241545닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241606닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241618오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241631오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241479닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241646디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241646오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241744닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241747디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242625오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241820닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241620Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241955닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241709VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241736닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241693닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
13551정성태2/12/20242017닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...