모든 유형에 별칭 사용 (구현됨, 17.6 P3에 반영)
C# 12은 이제 다음의 코드가 합법입니다.
using Point = (int X, int Y);
https://github.com/dotnet/csharplang/blob/main/proposals/using-alias-types.md
C# 12은 이제 다음의 코드가 합법입니다.
using Point = (int X, int Y);
https://github.com/dotnet/csharplang/blob/main/proposals/using-alias-types.md
C# 12은 이제 다음의 코드와 같이 class, struct에서 생성자 매개변수를 지정할 수 있으며 내부에서 사용할 경우 적절하게 private 필드로 캡쳐 됩니다.
class TestClass(int x, int y);
record와 다른 점은 x
와 y
가 외부로 노출되지 않는다는 점입니다.
Visual Studio의 최신 미리보기 빌드로 csporj에 다음의 설정을 한 후 확인이 가능합니다.
<PropertyGroup>
<LangVersion>Preview</LangVersion>
</PropertyGroup>
https://github.com/dotnet/csharplang/blob/main/proposals/primary-constructors.md
C# 12에서는 이제 람다에서 기본 매개변수를 사용할 수 있습니다.
var addWithDefault = (int addTo = 2) => addTo + 1;
addWithDefault(); // 3
addWithDefault(5); // 6
https://github.com/dotnet/csharplang/blob/main/proposals/lambda-method-group-defaults.md
Visual Studio 2022 17.6 P3이 출시되면서 이제 미리보기로 확인할 수 있습니다.
<PropertyGroup>
<LangVersion>preview</LangVersion>
</PropertyGroup>
using Point = (int X, int Y);
Point x = (10, 15);
Point y = (20, 12);
var z = new Point(x.X + y.X, x.Y + y.Y);
Console.WriteLine(z);
using System;
public struct C {
public string P;
public static string M1() => nameof(P); // Legal
public static string M2() => nameof(P.Length); // error CS0120: An object reference is required for the non-static field, method, or property 'C.P'
}
위의 코드와 같이 정적 컨텍스트에서 인스턴스 멤버에 엑세스 할 경우 컴파일 오류가 발생하는 경우가 있습니다.
17.7 P1 이후 부터는 이 컴파일 오류는 발생하지 않습니다.
VS 17.7p1이 릴리스 되면서 개선된 기능을 테스트할 수 있게 되었습니다. 이제 인스턴스 멤버도 nameof 대상으로 사용할 수 있습니다.
Console.WriteLine(C.M1());
Console.WriteLine(C.M2());
public struct C
{
public string P;
public static string M1() => nameof(P); // Legal
public static string M2() => nameof(P.Length); // error CS0120: An object reference is required for the non-static field, method, or property 'C.P'
}
| 출력
P
Length
C# 12의 기능이 거의 확정되었습니다. 꽤 많은 기능이 C# 12에서 제외된다는 사실이 약간 슬프네요.
특히 반자동 속성(Semi auto properties)의 경우 꽤 많이 사용할 기능이라 이전 버전부터 기다렸는데 의외로 구현이 어려운가 봅니다.
드디어 컬렉션 리터럴이 C#에 도입되는군요. 한마디로 이제 목록을 [1, 2, 3] 형태로 쓸 수 있게 됩니다.
사전 형식도 [key: value, …]로 사용할 수 있습니다.
단순히 중괄호에서 대괄호로 변경된것이 아니라 이전에는 목록을 사용하려면 new xx[] 로 해서 무조건 힙을 사용할 수 밖에 없거나 stackalloc
으로 명시적 스택 할당을 해야 했다면 Span<T> 유형으로 받을 경우 작은 단위의 컬렉션은 암묵적으로 stackalloc
을 사용하게 됩니다.
https://github.com/dotnet/csharplang/blob/main/proposals/collection-expressions.md#span-types
드디어 컬렉션 표현식을 Visual Studio 2022 17.7 P5에서 테스트 해 볼 수 있습니다.
<PropertyGroup>
<LangVersion>Preview</LangVersion>
</PropertyGroup>
이전에는 이렇게 써야 했다면
var oList = new int[] { 1, 2, 3, 4, 5 };
이제는 다음과 같이 사용할 수 있습니다.
int[] nList = [1, 2, 3, 4, 5];
스택에 배열을 생성하는 것도 다음처럼 사용할 수 있게 되었습니다.
Span<int> sList = [1, 2, 3, 4, 5];
패턴일치에도 사용할 수 있습니다.
var result = sList is [1, .., 5];
제네릭별칭은 아직인가보군요
제네릭도 별칭이 됩니다.