Search code examples
c#non-nullable

Create Non-Nullable Types in C#


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


Solution

  • Note: this is an old answer! C# is in constant development, and now has support for non-nullable reference types. See comment by @Scott Langham, or the answer by @Brian Rosamilia.

    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.