- Home /
Need my function to work with different lists of different values (classes)
Hi. I am currently making a board-style educational game. In my game there are 3 different types of card (Calculations, Math Riddles and Math Problems). I have 3 sub-classes for each card type which all inherit from a Card base class. Then I saved all my cards in three different lists
The problem is that I wrote a function that needs to access each list of the cards, but as I have three different list of different types, I can't put the into an array of lists and use and index.
In the function I replace some asterisks in a string with numbers from an array.
After investigating I only have found 2 options 1: I copy and paste the exact function and change the list 2: I found something about making arrays of objects which can contain things from any type but they seem not very efficient
Any ideas? I want to make it as good as possible and I think there must be a better way, thank you for your time
   //This is when I declare the tree different lists
  public List<CalculationCard> CalculationCards = new List<CalculationCard>();
     public List<RiddleCard> RiddleCards = new List<RiddleCard>();
     public List<EnigmaCard> EnigmaCards = new List<EnigmaCard>();
     private string DisplayTask(int index, int dif) //Function I mentioned
     {
         string task = database.EnigmaCards[index].task;
         bool asteriscLeft = true;
         int count = 0, i;
 
         while (asteriscLeft)
         {
             i = task.IndexOf("*", 0); //Search the next asterisk
 
             if (i != -1)
             {
                 string n = database.EnigmaCards[0].numbers[dif][count]; //This enigmaCards is the list that I need to change
                 task = task.Remove(i, 1).Insert(i, n); //Replaces the asterisk with the correct number
                 count++;
             }
             else
             {
                 asteriscLeft = false;
             }
         }
 
         return task;
     }
Answer by Kishotta · Jul 04, 2017 at 06:26 PM
So if I understand correctly: CalculationCard, RiddleCard, and EnigmaCard all inherit from a Card class?
If so you can use List<Card> or Card[]. For Googling purposes, this is called polymorphism. 
Thanks! I did not know that you could do that. I just started using inheratance
Yes Inheritance is great in this way. You might also be interested in Interfaces. They are sort of like a light-weight inheritance scheme.
Your answer
 
 
             Follow this Question
Related Questions
How do I save an array of all different variables? 0 Answers
Instantiating objects from a class? (C#) 1 Answer
C# Class and Array 1 Answer
Error passing class in method c# 3 Answers
properly initializing my arrays (C#) 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                