Create Non-Nullable Types 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.

Leave a Comment

tech