2

Since I was wondering about the efficiency of certain operations on Nullable<T>, I went to check the reference source on the Microsoft site (and learned that HasValue and GetValueOrDefault don't involve any switching whereas .Value does). Looking through the file, I noticed that it is an immutable type with an implicit conversion from T,

 public static implicit operator Nullable<T>(T value) {
     return new Nullable<T>(value);
 }

which I suppose allows me to write a line like

int? x; 
x = 3;

However, this does not explain how

x = null;

works. Nullable is a value type, so in general, this is not allowed. Initially I expected an overload of operator= or something similar, but I could not figure out what the argument of that should be (apart from a Nullable<T>).

I guess then that the compiler knows about Nullables and treats them in a special way, but I would guess that the development team would have wanted to keep this to a minimum so I am wondering what exactly the compiler knows. How does it handle a line like x = null and what other things that I could not find in the reference implementation does it do behind the scenes?


CompuChip
  • 9,143
  • 4
  • 24
  • 48
  • `null` in this case interpreted as `default(Nullable)`. – user4003407 Nov 02 '15 at 14:14
  • Thanks @PetSerAl, but this only works for `Nullable`. I am not allowed to write `S s = null` for any other value type `S`. So I was wondering on what level this is handled for nullables, possibly with a link to (e.g. Roslyn) source. – CompuChip Nov 02 '15 at 14:21
  • @DStanley is it the CLR that interprets this, or the compiler? Because I assume that `default(Nullable) == new T()`, i.e. assigning `null` has the same effect as calling the default constructor explicitly. – CompuChip Nov 02 '15 at 14:23
  • 1
    @CompuChip [The compiler](http://tryroslyn.azurewebsites.net/#f:>il/K4Zwlgdg5gBAygTxAFwKYFsDcAoADsAIwBswBjGUogQxBBgGEYBvbGNmfYsmANwHswAExgBZABQBKZq3azIyAPwwqMALwwIwIkRyyAvtj1AAAA==). – i3arnon Nov 02 '15 at 14:34
  • @CompuChip Not sure what you want to know. According to C# specification **6.1.5 Null literal conversions: An implicit conversion exists from the null literal to any nullable type.** There is no such conversion from null literal to not nullable value type, so that you are not allowed to write `S s = null`. – user4003407 Nov 02 '15 at 14:37
  • @DStanley could you point me to the duplicate please? – CompuChip Nov 02 '15 at 14:37
  • @CompuChip The link should be above the question now. – D Stanley Nov 02 '15 at 14:40
  • 1
    @DStanley No, the CLR has nothing special going on here. It's the compiler binding an implicit conversion operator to the assignment. Having the CLR doing anything would imply that the binding wasn't done until runtime, which isn't the case. – Servy Nov 02 '15 at 14:42
  • @DStanley thanks, that answer covers everything I'm looking for :) – CompuChip Nov 02 '15 at 14:44

0 Answers0