0

I made a list of all the subclasses of a base class using reflection using the code shown below

List<Type> BotNames = typeof(BotPlayer).Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(BotPlayer))).ToList();

Each one of these subclasses has a ToString() override which works when I make use of a normal list of instances of these subclasses but when I try to output the contents of the reflection list using the ToString() method, it uses the Default ToString() method which gives outputs such as "Checkers.Model.BotPlayer1" when its override ToString() is meant to return "Level 1". The code below is what I tested the output on( keep in mind that I am working using a GUI)

            foreach (var item in BotNames)
        {
            Messages.Text = item.ToString();
        }

If I can properly override to ToString() method, I plan to use it on the combo-box within my GUI so the contents of the reflection list are displayed with the correct names. This is where how I have the list in the Designer code in case that is required

            this.Difficulty.Items.AddRange(BotNames.ToArray());

Difficulty is the name of the combo-box

Jumpman
  • 3
  • 3
  • You aren't calling `ToString` of the **instance**. You are calling `Type.ToString` (https://learn.microsoft.com/en-us/dotnet/api/system.type.tostring?view=netframework-4.7.2) - which you have no control over. Your best bet here is to use attributes. – mjwills Nov 05 '18 at 20:35
  • Possible duplicate of [Get the Description Attributes At Class Level](https://stackoverflow.com/questions/2863817/get-the-description-attributes-at-class-level) – mjwills Nov 05 '18 at 20:39
  • @mjwills but how would I get that to display every subclass on the list in the combo box the way I intend it to be displayed? – Jumpman Nov 05 '18 at 20:51
  • @Jumpman You added the `Description` attribute and tried following the technique shown in the answer? If not, please try it before further comments. The technique does work. I've used it many times. – mjwills Nov 05 '18 at 20:52
  • Another approach you may want to use is to declare them as constants instead - https://stackoverflow.com/a/41618045/34092 . – mjwills Nov 05 '18 at 20:54
  • @mjwills I've tried it and it works when it comes to outputting the list in messages or the like but how would i integrate it in the designer class for the GUI form in such a way that the combo box displays the contents of the list in this way as well – Jumpman Nov 05 '18 at 21:02
  • Did you try running the code in `Form_Load`? – mjwills Nov 05 '18 at 22:06

0 Answers0