This post will try to include recent updates in c# language.
Record types
C# 9.0 introduced record types. You can use the record
keyword to define a reference type that provides built-in functionality for encapsulating data. Record with immutable properties using positional parameters or standard property syntax.
public record Person(string FirstName, string LastName);
Record type offers the following features:
- Concise syntax for creating a reference type with immutable properties
- Behavior useful for a data-centric reference type:
- Value equality
- Concise syntax for nondestructive mutation
- Built-in formatting for display
- Support for inheritance hierarchies
Init only setters
Init only setters provide consistent syntax to initialize members of an object. With C# 9.0, you can create init
accessors instead of set
accessors for properties and indexers.
You can declare init
only setters in any type you write.
public class Member
{
public int Id { get; init; }
public string Name { get; init; }
public string Address { get; init; }
}
Callers can use property initializer syntax to set the values, while still preserving the immutability:
Member memberObj = new Member {
Id = 1,
Name=”Adam”,
Address=”NY”
};
An attempt to change an observation after initialization results in a compiler error:
// Error! CS8852.
memberObj.Address = “Boston”
Init-only setters can be useful to set base class properties from derived classes. They can also set derived properties through helpers in a base class.
Top-level statements
Top-level statements remove unnecessary ceremony from applications. for example
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Hello World!”);
}
}
}
There’s only one line of code that does anything. With top-level statements, you can replace all that boilerplate as shown below.
System.Console.WriteLine(“Hello World!”);