How to create non-nullable value types like int, bool, etc. in C#?

有帮助吗?

解决方案

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.

其他提示

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

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top