Features of C# 9.0 – Part 1
Features of C# 9.0 – Part 1
Microsoft release C# version 9.0 in November 2020 with some exciting features. Let’s see some of them in this blog –
|
A record is a new C# data type that is immutable by default. The equality between Records is compared by structure or by reference equality.
Example –
Publicrecord Employee(stringName, intAge); public recordEmployee(stringName, intAge) {public string Name { get; set; } = Name; public int Age{ get; set; } = Age; } var employee1 = newEmployee("Parth Jolly", 29); var employee2= newEmployee("Siddharth Jolly", 25);
Console.WriteLine(employee1 == employee2); Console.WriteLine(employee1.Equals(employee2)); Console.WriteLine(ReferenceEquals(employee1, employee2)); // Changing the value varemployee3 = employee1 with{ Age = 35}; Console.WriteLine(employee1 == employee3); var(name, age) = employee3; employee1.Age = 35; publicrecord EmployeeInherit(string Name, int Age, string Country): Employee(Name, Age); varemployeeInherited = new EmployeeInherit(“Parth Jolly”, 29 , “India”); Console.WriteLine(employee1 == employeeInherited);
This feature allows the developer to use delegate* for the declaration of function pointers.
Example – unsafe class FunctionPtr { static int GetLength(string str) => str.Length; delegate* fnPtr=&GetLength; PublicvoidDemo() { Console.WriteLine(fnPtr("Parth")); } }
Output – 4
There are some enhancements to Pattern Matching which are introduced in C# 9. These are –
Example –
Objectcheck= new int(); var getType= checkswitch { string=> "string", int=> "int" }; Console.WriteLine(getType); Output –int And patterns: They are used to represent the logical “and” of the two sub-patterns.
Example –
varemployee = newEmployee("Parth", 29); varage= employeeswitch { Employee(_, <18) => "less than 18", ("Parth",_) and (_,>18)=>"Parth is greater than 18" }; Console.WriteLine(age);
Output -Parth is greater than 18
Example –
var employee = new Employee("Parth", 29); varage= employee switch { Employee(_, <18) => "less than 18", ("Parth",_) or (_,>18)=>"Parth is greater than or equal to 18" }; Console.WriteLine(age);
Output - Parth is greater than or equal to 18
Example –
var employee = new Employee("Parth", 29); varwho = employeeswitch { not("Parth", 29) => "who’s this”, _=>"It’s me" }; Console.WriteLine(who);
Output –It’s me
Example –
public record IsNumberFive(boolvalid, intNumber); varisNumberFive = newIsNumberFive(true, 5); varn = isNumberFive switch { ((_,>1and <5) and (_,>5and <9)) or (_,5) => "It is 5", _=> "It is not 5" }; Console.WriteLine(n);
Output –It is 5
Example –
var employee1 = new Employee("Parth", 29); var employee2 = new Employee("Siddharth", 18); var age = employee1 switch { Employee(_, < 18) => "age is less than 18", (_, > 18) => "age is greater than 18", (_, 18) => "age is 18 years old" }; Console.WriteLine(age);
Output -age is greater than 18
|
|
