Những điểm mới trong C# 9
(1) Visual Studio
Cần sử dụng Visual Studio bản preview bản mới nhất, sửa lại file *.csproj
thành
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>9.0</LangVersion>
</PropertyGroup>
</Project>
(2) Tính năng Target Typing
File Program.cs
Cú pháp cũ
namespace csharp9.old1
{
class Program1Old
{
void MyMethod()
{
Person person = new Person(); //<-- Trong C# 8.
}
}
class Person
{
public string FirstName { get; set; }
}
}
Cú pháp mới
namespace csharp9.new1
{
class ProgramNew
{
void MyMethod()
{
Person person = new(); //<-- Trong C# 9.
}
}
class Person
{
public string FirstName { get; set; }
}
}
(3) Tính năng Init-only property
Cách cũ
using System;
namespace csharp9.old2
{
class Program2Old
{
static void Main(string[] args)
{
var person = new Person("Nguyễn Văn A");
person.Name = "xx";
Console.WriteLine(person.Name);
}
}
public class Person
{
public Person(string name)
{
this.Name = name;
}
public string Name { get; set; } // Trong C# 8.
}
}
Cách mới trong C# 9
using System;
namespace csharp9.new2
{
class Program
{
public static void Main(string[] args)
{
var person = new Person("Tran Van B");
Console.WriteLine(person.Name);
}
}
public class Person
{
public Person(string name)
{
this.Name = name;
}
public string Name { get; init; } // Trong C# 9.
}
}
(4) Từ khóa "is" và "and"
using System;
namespace csharp9.new3
{
class Program
{
public static void Main(string[] args)
{
int value = 42;
switch (value)
{
case <= 0:
Console.WriteLine("Less than or equal to 0");
break;
case > 0 and <= 10:
Console.WriteLine("More than 0 but less than or equal to 10");
break;
default:
Console.WriteLine("More than 10");
break;
}
var message = value switch
{
<= 0 => "Less than or equal to 0",
> 0 and <= 10 => "More than 0 but less than or equal to 10",
_ => "More than 10"
};
Console.WriteLine(message);
if (value > 0 && value <= 10) // Trong C# 8.
{
Console.WriteLine("More than 0 but less than or equal to 10");
}
if (value is > 0 and <= 10) // Trong C# 9.
{
Console.WriteLine("More than 0 but less than or equal to 10");
}
}
}
}
(5) Tính năng Record Object
using System;
namespace csharp9
{
class RecordObject
{
static void Main(string[] args)
{
var book = new Book { Title = "Chí Phèo", Author = "Nam Cao", ISBN = "8935092514741" };
var newBook = book with { Title = "Đôi lứa xứng đôi" }; // Trong C# 9. Record Object.
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine(newBook.Title);
}
}
public record Book
{
public string Title { get; init; }
public string Author { get; init; }
public string ISBN { get; init; }
}
}
Source code: https://github.com/donhuvy/csharp9.git
All Rights Reserved