Undefined values: Difference between revisions
Content added Content deleted
(→{{header|CSharp}}: elaborated) |
|||
Line 2: | Line 2: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
In C# it's important to see the difference between reference and value types. For reference types (class instances) there is <code>null</code> as a general undefined reference. |
|||
When a basic type is suffixed by a question mark the type is marked nullable and gains an additional NULL value in addition to its usual allowed values. |
|||
<lang csharp> |
<lang csharp>string foo = null;</lang> |
||
Dereferencing a null reference will throw a <code>NullReferenceException</code>. |
|||
⚫ | |||
if(NULL == answer) { |
|||
This can't be used normally for value types (<code>int</code>, <code>double</code>, <code>DateTime</code>, etc.) since they are no ''references,'' so the following is a compiler error: |
|||
⚫ | |||
<lang csharp>int i = null;</code> |
|||
} |
|||
With .NET 2.0 there is an additional <code>Nullable<T></code> structure which enables those semantics for value types as well: |
|||
⚫ | |||
<lang csharp>int? answer = null; |
|||
if (answer == null) { |
|||
⚫ | |||
⚫ | |||
There is a bit syntactic sugar involved here. The <code>?</code> after the type name signals the compiler that it's a ''nullable'' type. This only works for value types since reference types are nullable due to their very nature. |
|||
But since value types still can't actually ''have'' a <code>null</code> value this gets converted into the following code by the compiler: |
|||
<lang csharp>Nullable<int> answer = new Nullable<int>(); |
|||
if (!answer.HasValue) { |
|||
⚫ | |||
}</lang> |
|||
So it's a little compiler magic but in the end works just as one would expect. |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |