Microsoft MVP성태의 닷넷 이야기
.NET Framework: 760. Microsoft Build 2018 - The future of C# 동영상 내용 정리 [링크 복사], [링크+제목 복사]
조회: 13841
글쓴 사람
정성태 (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)
12721정성태7/20/20217649오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/20216984Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/20216139오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/20216758개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/20216731Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
12716정성태7/17/20217528개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법파일 다운로드1
12715정성태7/17/20219244오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
12714정성태7/16/20217950오류 유형: 735. VCRUNTIME140.dll, MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll이 없어 exe 실행이 안 되는 경우
12713정성태7/16/20218504.NET Framework: 1077. C# - 동기 방식이면서 비동기 규약을 따르게 만드는 Task.FromResult파일 다운로드1
12712정성태7/15/20217907개발 환경 구성: 579. Azure - 리눅스 호스팅의 Site Extension 제작 방법
12711정성태7/15/20218244개발 환경 구성: 578. Azure - Java Web App Service를 위한 Site Extension 제작 방법
12710정성태7/15/202110019개발 환경 구성: 577. MQTT - emqx.io 서비스 소개
12709정성태7/14/20216687Linux: 42. 실행 중인 docker 컨테이너에 대한 구동 시점의 docker run 명령어를 확인하는 방법
12708정성태7/14/202110041Linux: 41. 리눅스 환경에서 디스크 용량 부족 시 원인 분석 방법
12707정성태7/14/202177255오류 유형: 734. MySQL - Authentication method 'caching_sha2_password' not supported by any of the available plugins.
12706정성태7/14/20218565.NET Framework: 1076. C# - AsyncLocal 기능을 CallContext만으로 구현하는 방법 [2]파일 다운로드1
12705정성태7/13/20218682VS.NET IDE: 168. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 - 두 번째 이야기
12704정성태7/12/20217833개발 환경 구성: 576. Azure VM의 서비스를 Azure Web App Service에서만 접근하도록 NSG 설정을 제한하는 방법
12703정성태7/11/202113473개발 환경 구성: 575. Azure VM에 (ICMP) ping을 허용하는 방법
12702정성태7/11/20218598오류 유형: 733. TaskScheduler에 등록된 wacs.exe의 Let's Encrypt 인증서 업데이트 문제
12701정성태7/9/20218255.NET Framework: 1075. C# - ThreadPool의 스레드는 반환 시 ThreadStatic과 AsyncLocal 값이 초기화 될까요?파일 다운로드1
12700정성태7/8/20218641.NET Framework: 1074. RuntimeType의 메모리 누수? [1]
12699정성태7/8/20217467VS.NET IDE: 167. Visual Studio 디버깅 중 GC Heap 상태를 보여주는 "Show Diagnostic Tools" 메뉴 사용법
12698정성태7/7/202111448오류 유형: 732. Windows 11 업데이트 시 3% 또는 0%에서 다운로드가 멈춘 경우
12697정성태7/7/20217339개발 환경 구성: 574. Windows 11 (Insider Preview) 설치하는 방법
12696정성태7/6/20217891VC++: 146. 운영체제의 스레드 문맥 교환(Context Switch)을 유사하게 구현하는 방법파일 다운로드2
... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...