C# 6.0 New Features
조만간 릴리즈될 C# 6.0 (현재 Preview 공개)의 new feature들을 보니, 그동안 불편했던 부분이 많이 개선이 되고 있음을 느낄 수 있었습니다.
재밌고 유용한 내용들을 모아보았습니다.
Static Using Syntax
기존에 using 지시자는 namespace에 사용할 수 있었습니다. 이제는 static 클래스에도 사용이 가능해졌습니다.
예를 들어 System 네임스페이스에 있는 static class Console에 using을 사용하면, 코드에서 Console.WriteLine() 대신 WriteLine()를 사용할 수 있습니다.
물론, 커스텀 클래스에도 적용이 가능합니다.
https://dotnetfiddle.net/tYMyBB
usnig System.Console; | |
namespace Test | |
{ | |
class Program | |
{ | |
public static void Main() | |
{ | |
WriteLine("test"); | |
} | |
} | |
} |
Auto Property Initializers
가장 마음에 드는 기능 중에 하나입니다. 기존에는 프로퍼티를 선언과 동시에 초기화할 수가 없어서, 생성자에서 초기화를 하였습니다.
하지만 이제는 생성과 동시에 초기화를 할 수가 있게 되었습니다.
https://dotnetfiddle.net/2hDVTJ
using System.Console; | |
namespace Test | |
{ | |
class Program | |
{ | |
public static int propertyValue { get; set; } = 100; | |
public static void Main() | |
{ | |
WriteLine(propertyValue); | |
} | |
} | |
} |
Dictionary Initailizers
Dictionary의 초기화 방법이 추가되었습니다. 기존 방식은 아래와 같은데, 초기 아이템이 많아질 수록, key 혹은 value가 클래스 타입일 수록 코드가 복잡했습니다.
using System.Collections.Generic; | |
namespace Simple | |
{ | |
class Program | |
{ | |
public static void Main() | |
{ | |
Dictionary<int, string> dic = new Dictionary<int, string>() | |
{ | |
{0, "zero"}, | |
{1, "one"}, | |
{2, "two"} | |
}; | |
} | |
} | |
} |
새로 추가된 초기화 방법은 다음과 같은데, 가독성이 좀 더 나아진 느낌입니다.
https://dotnetfiddle.net/23VUxF
using System.Collections.Generic; | |
namespace Simple | |
{ | |
class Program | |
{ | |
public static void Main() | |
{ | |
Dictionary<int, string> dic = new Dictionary<int, string>() | |
{ | |
[0] = "zero", | |
[1] = "one", | |
[2] = "two" | |
}; | |
} | |
} | |
} |
Null Condition Operator
null 체크 오퍼레이터가 추가되어 if (obj == null)과 같은 코드를 줄일 수가 있습니다.
using System.Console; | |
namespace Simple | |
{ | |
class Program | |
{ | |
public static void Main() | |
{ | |
string testString = null; | |
int? length = testString?.Length; | |
WriteLine(length??-1); | |
} | |
} | |
} |
Expression Bodied Functions and Properties
Expresson Bodied Functions과 Properties가 새로 추가되었습니다.
using System.Console; | |
namespace Test | |
{ | |
class Program | |
{ | |
public static ToText() => "AsString()"; | |
public static Text => "Text"; | |
public static void Main() | |
{ | |
WriteLine(ToText()); | |
WriteLine(Text); | |
} | |
} | |
} |
'In to the C#' 카테고리의 다른 글
[C#] REST API 만들기 (0) | 2014.02.13 |
---|---|
[C#] Task의 작업완료 (2) | 2014.01.26 |
[C#] Action, Func 그리고 Task (0) | 2014.01.26 |
[C#] Attribute : 속성 (0) | 2014.01.24 |
Lazy Initialization (0) | 2014.01.20 |