สรุปฟีเจอร์ C# 8.0

wk
2 min readOct 19, 2019

--

1. Using Declaration

C# < 8.0 ใช้ Using block

using(var stream = new MemoryStream(...)) {
...
...
}
using (var stream = new MemoryStream(...)
...

C# 8.0 ลดเหลือบรรทัดเดียว

using var stream = new MemoryStream(...);

2̷.̷ ̷D̷i̷s̷p̷o̷s̷a̷b̷l̷e̷ ̷P̷a̷t̷t̷e̷r̷n̷

C# < 8.0 การประกาศ keyword using จะใช้ได้กับคลาสที่ implement IDisposable เท่านั้น เช่น

class A7 : IDisposable {
public void Dispose() { }
}
using (var a7 = new A7()) { }

C# 8.0 สามารถใช้ได้กับทุกคลาสที่ประกาศฟังก์ชัน Dispose

class A8 {
public void Dispose() { }
}
using var a8 = new A8();

3. Nullable Reference Type

C# < 8.0 โอเปอร์เรเตอร์ Nullable (?) จะใช้ได้กับ Value type เท่านั้น เช่น

int i = 0;
bool b = false;
int? nullableInt = null;
bool? nullableBool = null;

C# 8.0 สามารถใช้ Nullable(?) กับ Reference type

string text = "Value";
string? nullableText = null;

ถ้าต้องการเปิด Feature นี้ทั้งโปรเจค ให้เพิ่ม NullableContextOptions ในไฟล์ csproj

<PropertyGroup> 
<NullableContextOptions>enable</NullableContextOptions>
</PropertyGroup>

แต่ถ้าต้องการใช้เฉพาะบางไฟล์ให้ใช้ Nullable pragma โดยเขียนไว้ที่หัวของไฟล์

#nullable enable

4. Null-forgiving Operator (!.)

C# < 8.0 ไม่มี

C# 8.0 ในกรณีที่ Instance เป็น Nullable แต่เรามันใจว่าไม่ใช่ Null แน่ ๆ สามารถใช้เครื่องหมาย Bang (!) เพื่อปิด Warning ของ Compiler ได้

string? nullableText = GetValue();
var length = nullableText!.Length

5. Null-coalescing Assignment Operator

C# < 8.0

List<int> numbers = null;
numbers = numbers ?? new List<int>();

C# 8.0

List<int> numbers = null;
numbers ??= new List<int>();

6. Range Operator

C# < 8.0 ไม่มี

C# 8.0 : เป็น Operator ที่ใช้สำหรับเข้าถึง Element ของ Collection

Syntax

array[start..end]
array[start..]
array[..end]
array[..]

เช่น

var array = new string[] {
"Item1",
"Item2",
"Item3",
"Item4",
"Item5",
};
var item1 in array[1..3];
var item2 in array[1..];
var item3 in array[..];
var item4 in array[..3];
var item5 in array[1..^1]
var range1 = 1..3;
var range2 = 1..;

7. Switch Expression

C# < 8.0 ไม่มี

C# 8.0 : Switch expression เป็นคำสั่งที่คล้ายกับ Switch case ต่างกันที่ Switch expression จะ Return ค่า ทำให้สามารถใช้เขียน Pattern matching คล้ายกับภาษา Functional

var token = (true, true);
var rs = token switch {
(true, true) => true,
(true, false) => false,
(false, true) => false,
(false, false) => false
};

8. Default Interface Methods

C# < 8.0 ไม่มี

C# 8.0

interface IService {
void Start();
void Stop();
void Restart() {
Stop();
Start();
}
}

9. Static Local Function

C# < 8.0 ไม่มี

C# 8.0

int Process(int a) {
static int Add2(int x) => x + 2;
return Add2(a);
}
Console.WriteLine(Process(100));

10. Interpolated Verbatim Strings

C# < 8.0 เครื่องหมาย $ ต้องอยู่ก่อน @

var name = "wk";
var text1 = $@"
Hello {name}
";

C# 8.0 สามารถใช้ $@ หรือ @$ สลับกันได้

var name = "wk";
var text1 = @$"
Hello {name}
";
var text2 = $@"
Hello {name}
";

--

--

No responses yet