Associated Arrays and null. dict == null vs. dict is null
Brother Bill
brotherbill at mail.com
Sat Nov 1 12:23:07 UTC 2025
What does dict == null mean vs dict is null, when dict is a
dictionary?
Is this table accurate?
```
dict == null dict is null # elements memory allocated
true true 0 no
true false 0 yes
false false 1+ yes
false true (Is this a possibility, and if so,
how to create it?)
```
source/app.d
```
import std.stdio;
void main()
{
// value[key]
int[string] dayNumbers =
// key : value
[
"Monday": 0, "Tuesday": 1, "Wednesday": 2,
"Thursday": 3, "Friday": 4,
"Saturday": 5, "Sunday": 6
];
dayNumbers.remove("Tuesday");
// writeln(dayNumbers["Tuesday"]); // ← run-time ERROR
dayNumbers.clear; // Remove all elements
// Best to check length to see if associative array is empty,
rather than comparing to null.
// Checking to see if an associative array is null only tells
you if it has been allocated memory.
// dayNumbers has no elements
writeln("dayNumbers == null? ", dayNumbers == null); //
true
// dayNumbers has allocated memory, although no elements
writeln("dayNumbers is null? ", dayNumbers is null); //
false
writeln("dayNumbers.length: ", dayNumbers.length); // 0
writeln;
int[string] aNonInitializedDictionary;
writeln("aNonInitializedDictionary is null? ",
aNonInitializedDictionary is null); // true
writeln("aNonInitializedDictionary == null? ",
aNonInitializedDictionary == null); // true
writeln("aNonInitializedDictionary.length: ",
aNonInitializedDictionary.length); // 0
writeln;
int[string] aPopulatedDictionary;
aPopulatedDictionary["Alpha"] = 1;
writeln("aPopulatedDictionary is null? ",
aPopulatedDictionary is null); // false
writeln("aPopulatedDictionary == null? ",
aPopulatedDictionary == null); // false
writeln("aPopulatedDictionary.length: ",
aPopulatedDictionary.length); // 0
}
```
Console output
```
dayNumbers == null? true
dayNumbers is null? false
dayNumbers.length: 0
aNonInitializedDictionary is null? true
aNonInitializedDictionary == null? true
aNonInitializedDictionary.length: 0
aPopulatedDictionary is null? false
aPopulatedDictionary == null? false
aPopulatedDictionary.length: 1
```
More information about the Digitalmars-d-learn
mailing list