There is a Hashtable variable, the List <> is added to it. Why is it not output <> when outputting from Hashtable?

static void Main(string[] args) { Hashtable catalog = new Hashtable(); for (int i = 0; i < 5; i++)//просто создаётся лист с двумя структурами-мусик и добавляется в каталог-Хештейбл { List<Music> disk = new List<Music>() { new Music() { Author = $"a{i}", Song = $"asong{i}" }, new Music() { Author = $"b{i}", Song = $"bsong{i}" } }; //PrintDisk(disk); //тут не ругается и всё работает catalog.Add($"Disk{i}", disk); } //PrintDisk(catalog["Disk1"]);//ругается а на верху перед добавление нет Console.ReadKey(); } struct Music { public string Author; public string Song; } static void PrintDisk(List<Music> disk) { foreach (Music x in disk) { Console.WriteLine("Author: {0, 10}; Song: {1, 8}", x.Author, x.Song); } } 
  • It is necessary to bring manually to the type, in fact the object stored there. Therefore, it is advised to use a Dictionary, rather than a hash table. - Sergey

1 answer 1

Write so PrintDisk((List<Music>)catalog["Disk1"]);

The object gets the key from HashTable , and the method takes as input the List<Music> , so you need to cast to your type. Or use Dictionary<TKey,TValue> .

  • I also thought that you need to use a directory. But in the lab given this type of collection. Damn, but I tried to convert it at the beginning so .... Apparently I made a mistake and thought that it wasn’t roby - LORD
  • 3
    @LORD - laboratory workbook is probably outdated long time ago. - Alexander Petrov
  • 2
    @LORD: Untyped Hashtable is Mesozoic. It makes no sense not to use the Dictionary . - VladD