Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason not all value types are nullable?

Tags:

.net

nullable

Is there any penalty, such that you should only set them as nullable when you really need it?

Thanks

like image 769
devoured elysium Avatar asked Jul 04 '09 15:07

devoured elysium


People also ask

Are Value types nullable?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

What is non-nullable value 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.

Are all objects nullable?

In many cases in fact, objects have reference types, can contain a null value, and thus are all nullable; none of these have a Nullable type.

Are Value types nullable C#?

C# - Nullable Types. As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error. C# 2.0 introduced nullable types that allow you to assign null to value type variables.


1 Answers

Various reasons:

  • History: Nullable<T> didn't exist until .NET 2.0, and it can't break existing code - especially with the different boxing rules for Nullable<T>
  • Meaning: if I want an int, I might not want it to be nullable... I want it to be an int, and I don't want to have to check-for/handle nulls
  • Space: it adds extra cost to each struct... in particular, imagine a byte[], and now consider if byte was nullable - lots of extra overhead; *plus it would stop you doing blits etc*
  • Performance: Nullable<T> adds lots of extra penalties; in particular lots of hidden calls to .HasValue and .Value / .GetValueOrDefault(); this is shown in particular in the "lifted operators" - i.e. x + y becomes something like below, which adds up for tight loops etc:

    (x.HasValue && y.HasValue) ? (x.GetValueOrDefault() + y.GetValueOrDefault()) : null

Likewise, x == y has to check:

  • if both null => true
  • if one null => false
  • otherwise use == on GetValueOrDefault() of each

lots of overhead....

like image 84
Marc Gravell Avatar answered Sep 23 '22 08:09

Marc Gravell