Microsoft MVP성태의 닷넷 이야기
.NET Framework: 760. Microsoft Build 2018 - The future of C# 동영상 내용 정리 [링크 복사], [링크+제목 복사]
조회: 13935
글쓴 사람
정성태 (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]

... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12678정성태6/17/20218087.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/20219571VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
12676정성태6/16/20219633VC++: 143. ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법파일 다운로드1
12675정성태6/16/20217645Java: 20. maven package 명령어 결과물로 (war가 아닌) jar 생성 방법
12674정성태6/15/20218416VC++: 142. DEFINE_GUID 사용법
12673정성태6/15/20219588Java: 19. IntelliJ - 자바(Java)로 만드는 Web App을 Tomcat에서 실행하는 방법
12672정성태6/15/202110707오류 유형: 725. IntelliJ에서 Java webapp 실행 시 "Address localhost:1099 is already in use" 오류
12671정성태6/15/202117435오류 유형: 724. Tomcat 실행 시 Failed to initialize connector [Connector[HTTP/1.1-8080]] 오류
12670정성태6/13/20218967.NET Framework: 1071. DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제파일 다운로드1
12669정성태6/11/20218939.NET Framework: 1070. 사용자 정의 GetHashCode 메서드 구현은 C# 9.0의 record 또는 리팩터링에 맡기세요.
12668정성태6/11/202110694.NET Framework: 1069. C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작파일 다운로드2
12667정성태6/10/20219308.NET Framework: 1068. COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결파일 다운로드1
12666정성태6/10/20217941.NET Framework: 1067. 별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출파일 다운로드1
12665정성태6/9/20219260.NET Framework: 1066. Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약파일 다운로드1
12664정성태6/9/20217545오류 유형: 723. COM+ PIA 참조 시 "This operation failed because the QueryInterface call on the COM component" 오류
12663정성태6/9/20219042.NET Framework: 1065. Windows Forms - 속성 창의 디자인 설정 지원: 문자열 목록 내에서 항목을 선택하는 TypeConverter 제작파일 다운로드1
12662정성태6/8/20218214.NET Framework: 1064. C# COM 개체를 PIA(Primary Interop Assembly)로써 "Embed Interop Types" 참조하는 방법파일 다운로드1
12661정성태6/4/202118827.NET Framework: 1063. C# - MQTT를 이용한 클라이언트/서버(Broker) 통신 예제 [4]파일 다운로드1
12660정성태6/3/20219933.NET Framework: 1062. Windows Forms - 폼 내에서 발생하는 마우스 이벤트를 자식 컨트롤 영역에 상관없이 수신하는 방법 [1]파일 다운로드1
12659정성태6/2/202111211Linux: 40. 우분투 설치 후 MBR 디스크 드라이브 여유 공간이 인식되지 않은 경우 - Logical Volume Management
12658정성태6/2/20218646Windows: 194. Microsoft Store에 있는 구글의 공식 Youtube App
12657정성태6/2/20219923Windows: 193. 윈도우 패키지 관리자 - winget 설치
12656정성태6/1/20218151.NET Framework: 1061. 서버 유형의 COM+에 적용할 수 없는 Server GC
12655정성태6/1/20217688오류 유형: 722. windbg/sos - savemodule - Fail to read memory
12654정성태5/31/20217717오류 유형: 721. Hyper-V - Saved 상태의 VM을 시작 시 오류 발생
12653정성태5/31/202110354.NET Framework: 1060. 닷넷 GC에 새롭게 구현되는 DPAD(Dynamic Promotion And Demotion for GC)
... 31  32  33  34  35  36  37  [38]  39  40  41  42  43  44  45  ...