Anonymous user
Undefined values: Difference between revisions
→{{header|CSharp}}: elaborated
(→{{header|CSharp}}: elaborated) |
|||
Line 2:
=={{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.
<lang csharp>string foo = null;</lang>
Dereferencing a null reference will throw a <code>NullReferenceException</code>.
int? answer = NULL;▼
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:
answer = 42;▼
<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>▼
<lang csharp>int? answer = null;
if (answer == null) {
▲}</lang>
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}}==
|