Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do nullable types work in C#?

Tags:

What is the behind-the-scenes difference between 'int?' and 'int'? Is 'int?' a somehow a reference type?

like image 902
Mike Comstock Avatar asked Sep 21 '08 04:09

Mike Comstock


People also ask

What is the purpose of a nullable type?

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 .

How are nullable types declared in C#?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

What do you mean by nullable type?

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type.

Should I use nullable reference types?

Although using nullable reference types can introduce its own set of problems, I still think it's beneficial because it helps you find potential bugs and allows you to better express your intent in the code. For new projects, I would recommend you enable the feature and do your best to write code without warnings.


2 Answers

? wraps the value type (T) in a Nullable<T> struct:

http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

like image 92
core Avatar answered Oct 18 '22 16:10

core


In addition to "int?" being a shortcut for "Nullable", there was also infrastructure put into the CLR in order to implicitly and silently convert between "int?" and "int". This also means that any boxing operation will implicitly box the actual value (i.e., it's impossible to box Nullable as Nullable, it always results in either the boxed value of T or a null object).

I ran into many of these issues when trying to create Nullable when you don't know T at compile time (you only know it at runtime). http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html

like image 27
Brad Wilson Avatar answered Oct 18 '22 16:10

Brad Wilson