Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Non-Nullable Types in C#

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

like image 556
Navid Rahmani Avatar asked Jun 15 '11 23:06

Navid Rahmani


People also ask

What is a non-nullable type?

Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.

What is non-nullable type in C#?

Some languages have non-nullable reference types; if you want to represent a null, you use a different data type (equivalent to option<string> found in many languages), so you communicate and enforce null-checking through the type system at compile time.

What is #nullable disable?

Nullable disable as the default: disable is the default if you don't add a Nullable element to your project file. Use this default when you're not actively adding new files to the codebase. The main activity is to update the library to use nullable reference types.

What is the use of HasValue in C#?

HasValue indicates whether an instance of a nullable value type has a value of its underlying type. Nullable<T>. Value gets the value of an underlying type if HasValue is true . If HasValue is false , the Value property throws an InvalidOperationException.


2 Answers

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.

like image 94
Miguel Angelo Avatar answered Oct 28 '22 23:10

Miguel Angelo


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

like image 36
Brian Rosamilia Avatar answered Oct 28 '22 22:10

Brian Rosamilia