Avatar ·

Warum ist Dictionary<TKey, TValue> besser als Hashtable in C#?

Hallo zusammen! Ich habe vor kurzem angefangen, C# zu lernen und bin auf Collections gestoßen. Ich sehe, dass es `Hashtable` (aus `System.Collections`) und `Dictionary` (aus `System.Collections.Generic`) gibt. Beide speichern anscheinend Key-Value-Paare, aber überall wird empfohlen, `Dictionary` zu verwenden.\n\nIch habe ein kleines Beispiel mit `Hashtable` geschrieben:\n\n```csharp\nHashtable table = new Hashtable();\ntable.Add("key1", 123);\ntable.Add("key2", "string");\n\nforeach (DictionaryEntry entry in table)\n{\n Console.WriteLine($"{entry.Key}: {entry.Value}");\n}\n```\n\nUnd mit `Dictionary`:\n\n```csharp\nDictionary dict = new Dictionary();\ndict.Add("key1", 123);\ndict.Add("key2", 456); // hier ist alles streng typisiert\n\nforeach (KeyValuePair kvp in dict)\n{\n Console.WriteLine($"{kvp.Key}: {kvp.Value}");\n```