Create Non-Nullable Types in C#

*爱你&永不变心* 提交于 2019-11-28 21:02:37

Yes, these are called struct.

Structs are value types, just like int, bool and others.

They have some rules/recommendations related to them: (I think these are the most important)

  • a struct is passed and assigned by value, when not using ref or out keywords... this means that everything you put inside a struct will be copied when assigning or passing it to a method. That is why you should not make large structs.

  • you cannot define a parameterless constructor for a struct in C#

  • structs are better to be immutable, and have no property setters. You can get into real trouble by making mutable structs.

Other rules can be found within Microsoft docs about structs.

As for non-nullable reference types... this is not possible. You must check for nulls inside your code, manually.

You can define a struct:

A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:

public struct Book
{
    public decimal price;
    public string title;
    public string author;
}

However, you can't define aliases like int for System.Int32 and need to refer with the full name MyNamespace.Book (or Book with using MyNamespace;) to your struct.

Brian Rosamilia

7 years later and this is now possible

  • Install .NET Core 3.0 which includes C# 8.
  • Set the language version to 8.0: 8.0 to your .csproj file.
  • Add the property true (.to your csproj)

More details on his this affects writing code and your existing code here:

https://praeclarum.org/2018/12/17/nullable-reference-types.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!