头图

C# 11 Preview

C# 11 is nearing completion. This article covers what's new in Visual Studio 17.3 and what we didn't cover in the April Update for Visual Studio 17.2 and the February Update for Visual Studio 17.1 .
The new features in this preview follow the three investment themes of C# 11:

  • Object initialization improvements : No matter what rules you want to enforce for mutable and immutable members, you can more easily support constructors and object initializers in types. Features include:

    • Required member
    • ref field
  • Generic math support : You can write algorithms once for many number types. These functions make statistics, machine learning, and other math-intensive applications easier using C# and .NET. Features include:

    • Static abstract and static virtual members in interfaces
    • Relax right shift requirements
    • unsigned right shift operator
    • Value IntPtr]
  • Developer Productivity: We've added more language features to increase your productivity.
    New extended feature: nameof .

The following sections outline each function and link in Microsoft Docs , where you can read more. To try out these features, you need to have preview enabled in your project. This is explained in the What's New in C# 11 article in the documentation.

Object initialization improvements

The required member allows you to write classes and struct types that require the caller to set certain properties. Refer to this Person type:

 public class Person
{
    public string FirstName { get; init; }
    public string LastName {get; init; }
}

The caller should use object initializers to set the values of the FirstName and LastName properties. But before Visual Studio 17.3, the compiler could not force the caller to have these properties set. A constructor that requires arguments is the only way to ensure that the user sets the FirstName and LastName properties. The required members communicate to the compiler and caller that they must set these properties. Add the required modifier to the member declaration:

 public class Person
{
    public required string FirstName { get; init; }
    public required string LastName {get; init; }
}

All callers must contain object initializers for the FirstName and LastName properties, otherwise the compiler will issue an error. The compiler informs the caller that there are required members that are not initialized. Developers must address this issue immediately.

If the Person type was written for an earlier version and contains a constructor that sets properties, you can still use the required member. You should annotate any existing constructors with the SetsRequiredMembers attribute:

 public class Person
{
    public required string FirstName { get; init; }
    public required string LastName {get; init; }

    [SetsRequiredMembers]
    public Person(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }

    public Person() {}
}

SetsRequiredMembers attribute indicates that the constructor sets all required members. The compiler knows to use

 Person (string firstName, string lastName)

The caller of the constructor has set the required member. The parameterless constructor does not contain this property, so callers using this constructor must initialize all required members with an object initializer.

The above example uses properties, but you can also apply required members to field declarations.

This preview also includes initial implementations of ref fields and scoped values . These changes provide availability for the ref field in the --- ref struct type. You can also use the scoped keyword to limit the lifetime of the ref parameter. Feature proposals and updated changes now provide the best documentation for this feature. We found a few scenarios that required a language change to be safe to use. The updated changes will be available in a preview to be released at a later date, and the documentation will reflect the final design.

General Math Support

We added general math as a feature for motivating scenarios. You'll only use these functions directly in advanced scenarios, such as writing mathematical algorithms that work with many types of numbers. Otherwise, you will benefit indirectly because the runtime uses the following functions:

Adding static abstractions and virtual members to interfaces lays a lot of important groundwork for general mathematics. This feature allows interfaces to declare operators as well as other static methods. A class implementing an interface must provide an implementation of the 静态抽象 method just like any other method declared in the interface. The compiler resolves calls to 静态 methods (including operators) at compile time. There is no runtime dispatch mechanism like instance methods. The documentation provides more details on the specific language rules required to make this function work.

Other language features remove some of the differences in number types, making it easier to write general mathematical algorithms. The right shift operator no longer requires the second operand to be int , but any integer type will do! nint and nuint are the synonyms of System.IntPtr and System.UIntPtr respectively. These keywords can be used in place of these types. In fact, the new analyzer prompts you to choose keywords instead of type names. Finally, the unsigned right shift operator ( >>> ) avoids the cast when you do an unsigned shift.

Taken together, these changes and others like the check operator support the generic math runtime changes. Language improvements mean that the runtime team can make improvements to all numeric types in .NET. You can also take advantage of these features when your types implement contracts using operators or other static methods.

developer productivity

nameof operators can now be used with method parameters . This feature allows you to use the nameof operator in the property declaration of a method, as shown in the following example:

 [return:NotNullIfNotNull(nameof(url))]
string? GetTopLevelDomainFromFullUrl(string? url)

welcome

Please download the latest Visual Studio 2022 preview and install the .NET 7 preview, or you can install the .NET 7 latest preview separately. Once installed, you can try out the new features by creating or opening a C# project and setting LangVersion Preview .

This Visual Studio preview brings us one step closer to the full feature set of C# 11. We continue to invest in several themes in this release. We've made corrections based on the feedback you gave us. Now is a good time to download the preview to try out all the new features and give us your feedback. We are focusing on C# 11 and .NET 7 with final updates.


To learn more about what's new in C# 11, head over to the official documentation.

微软技术生态官方平台。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。

397 声望
960 粉丝
0 条评论
推荐阅读
限量红包封面开抢啦!祝你兔年好运连连
① 请先微信搜索关注“微软开发者MSDN”公众号② 选择你喜欢的技能,私信发送对应兔子名称(飞飞兔、灵灵兔、康康兔、美美兔、安安兔)③ 后台会自动弹出一张海报,请扫码领取封面

微软技术栈阅读 696

封面图
VS Code For Web 深入浅出 -- 进程间通信篇
在上一篇中,我们一起分析了 VS Code 整体的代码架构,了解了 VS Code 是由前后端分离的方式开发的。且无论前端是基于 electron 还是 web,后端是本地还是云端,其调用方式并无不同。

Duang4阅读 1.4k

VSCode 格式化哲学
当我们说「团队需要统一的代码样式」,大家都没有什么反对意见;但当问题变为「统一成什么样式?」时,大家的声音就嘈杂了起来。人们对于特定的编码方式很抵触,没有人喜欢花时间这样写代码,没人愿意接受别人的...

Cheri2阅读 608

VS Code For Web 深入浅出 -- Server 模块设计篇
在了解了 VS Code 的通信机制后,我们可以着手分析 VS Code Server 中各模块的实现以及设计思路了。<!-- more -->VSCode Server 模块设计通过之前的介绍我们可以了解到,VS Code 的能力是前后端分离的,这...

Duang1阅读 1.5k

VSCode For Web 深入浅出 -- 依赖注入设计
在阅读 VSCode 代码的过程中,我们会发现每一个模块中都有大量装饰器的使用,用来装饰模块以及其中依赖的模块变量。这样做的目的是什么呢?在这一篇中我们来详细分析一下。

Duang2阅读 1.6k

ASP.NET连接数据库(SQL Server)的操作
1.创建好项目后在我们的Web.config里面连接SQL Server数据库2.写入代码 {代码...} conStr是字段名字,后面连接需要,localhost是本地地址的意思,s是数据库中的表名。3.选中shujuku练习右击,选择添加,然后在选...

HealerHong3阅读 686评论 1

(持续更新,已更新至2022年11月26日)C语言经典题集合
(持续更新,最新时间2022年11月26日)1. 三个数由小到大排序输入任意3个整数,编程实现对这3个整数进行由小到大排序井将排序后的结果显示在屏幕上 {代码...} 2. a²+b²要求输入整数a和 b, 若a²+b²的结果大与100, ...

瞿小凯阅读 1.4k评论 2

封面图

微软技术生态官方平台。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。

397 声望
960 粉丝
宣传栏