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

... [196]  197 
NoWriterDateCnt.TitleFile(s)
40정성태7/23/200321823COM 개체 관련: 10. IE BHO 개체를 개발할 때, 인터넷 익스플로러가 아닌 탐색기에서 활성화 되는 문제 해결 [1]
41김성현7/24/200320654    답변글 COM 개체 관련: 10.1. [답변]: IE BHO 개체를 개발할 때, 인터넷 익스플로러가 아닌 탐색기에서 활성화 되는 문제 해결
42정성태7/29/200318595        답변글 COM 개체 관련: 10.2. feedback 을 받기 위해서 답변 기능을 가능하게 해두었습니다.
39정성태7/17/200324380VS.NET IDE: 5. 원격 제어 3가지 방법
38정성태7/17/200320913.NET Framework: 8. IIS 서버 재설치와 ASP.NET 서비스의 문제점
36정성태7/17/200321589.NET Framework: 7. 시행착오 - WebService 참조 추가 오류
35정성태7/17/200322104.NET Framework: 6. Win2000에서의 .NET COM+ 자동 등록 오류 발생 해결
34정성태7/17/200320777VS.NET IDE: 4. VC++ 원격 디버깅파일 다운로드1
33정성태7/17/200320931VS.NET IDE: 3. Win2000 NAT 서비스
32정성태7/17/200322145COM 개체 관련: 9. _bstr_t, CComBSTR, string 클래스 사용 [1]
31정성태7/17/200319230COM 개체 관련: 8. IDL 구문에서 구조체를 pack 하는 방법
30정성태7/17/200336487VC++: 7. [STL] vector 사용법 및 reference 사용예 [1]파일 다운로드1
28정성태7/17/200320894스크립트: 3. Programming Microsoft Internet Explorer 5 - CHM 파일
29정성태7/17/200320374    답변글 스크립트: 3.1. Programming Microsoft Internet Explorer 5 - 소스코드
27정성태7/17/200319294COM 개체 관련: 7. HTML Control에서 DELETE, 화살표 키 등이 안 먹는 문제
26정성태7/17/200320460COM 개체 관련: 6. WebBrowser 콘트롤에서 프레임을 구하는 소스
25정성태7/17/200318105COM 개체 관련: 5. C++ Attributes - Make COM Programming a Breeze with New Feature in Visual Studio .NET [2]파일 다운로드1
24정성태7/17/200321734.NET Framework: 5. (MHT 변환해서 가져온 글) .NET 의 COM+ 서비스 사용파일 다운로드1
23정성태7/17/200325420.NET Framework: 4. webservice.htc - HTML Script에서도 웹서비스 엑세스 [2]파일 다운로드1
22정성태7/17/200319955.NET Framework: 3. .NET Framework SDK 퀵 스타트 자습서
21정성태7/17/200319032.NET Framework: 2. 김현승님의 "ASP.NET & .NET EnterpriseServices & Remoting 코드 템플릿"
20정성태2/15/200526046VS.NET IDE: 2. Platform SDK 설치
19정성태7/17/200321980.NET Framework: 1. JScript.NET 강좌 사이트[영문]
18정성태7/17/200319395COM 개체 관련: 4. Exchanging Data Over the Internet Using XML [1]파일 다운로드1
17정성태7/17/200327348VC++: 6. Win32 API Hook - 소스는 "공개소스"에있습니다. [2]
16정성태7/17/200319669COM 개체 관련: 3. IE 툴밴드의 위치문제파일 다운로드1
... [196]  197