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

... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13148정성태10/26/20225647오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224765오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225609.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20225874오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/20225715.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/20226227오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/20224959도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/20226711.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/20226094C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/20225925.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/20227213.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/20225601.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
13136정성태10/7/20226175.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
13135정성태10/5/20226405.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
13134정성태10/4/20225135오류 유형: 820. There is a problem with AMD Radeon RX 5600 XT device. For more information, search for 'graphics device driver error code 31'
13133정성태10/4/20225455Windows: 211. Windows - (commit이 아닌) reserved 메모리 사용량 확인 방법 [1]
13132정성태10/3/20225328스크립트: 42. 파이썬 - latexify-py 패키지 소개 - 함수를 mathjax 식으로 표현
13131정성태10/3/20227991.NET Framework: 2052. C# - Windows Forms의 데이터 바인딩 지원(DataBinding, DataSource) [2]파일 다운로드1
13130정성태9/28/20225094.NET Framework: 2051. .NET Core/5+ - 에러 로깅을 위한 Middleware가 동작하지 않는 경우파일 다운로드1
13129정성태9/27/20225391.NET Framework: 2050. .NET Core를 IIS에서 호스팅하는 경우 .NET Framework CLR이 함께 로드되는 환경
13128정성태9/23/20227968C/C++: 158. Visual C++ - IDL 구문 중 "unsigned long"을 인식하지 못하는 #import파일 다운로드1
13127정성태9/22/20226418Windows: 210. WSL에 systemd 도입
13126정성태9/15/20227030.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
13125정성태9/14/20227238.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
13124정성태9/13/20226979.NET Framework: 2047. Golang, Python, C#에서의 CRC32 사용
13123정성태9/8/20227415.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...