0

For example, I have three classes: Animal, Dog and Cat; where Animal is an abstract class and inherits its properties to Dog and Cat. Say on my program, I have an arbitrary list of things that the user may input (I'm doing this on C# Form). So I store all the inputs, whether they are of class Cat or Dog, into my List<Animal>.

Now I would like to retrieve said instantiated class from List<Animal> and retrieve its original class, whether it's a Cat or a Dog. Is there a way to do that?

Richard
  • 7,037
  • 2
  • 23
  • 76

3 Answers3

5

In latest C# you can do:

Animal animal;
if (animal is Cat cat)
{
   cat.Meow();
}
Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
  • Is there a name for this syntax? – Richard Apr 23 '19 at 04:31
  • @RichardW the terminology is *Pattern matching*, you can find more information here [is (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is) – TheGeneral Apr 23 '19 at 04:37
3
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Animal> animals = new List<Animal> { new Cat(), new Cat(), new Dog(), new Cat(), new Dog() };

            var dogs = animals.OfType<Dog>().ToList();
            dogs.ForEach(dog => dog.Bark());

            var cats = animals.OfType<Cat>().ToList();
            cats.ForEach(cat => cat.Meow());

            var actualTypes = animals.Select(animal => animal.GetType()).ToList();
        }

        abstract class Animal { }

        class Dog : Animal { public void Bark() { } }

        class Cat : Animal { public void Meow() { } }
    }
}
CSDev
  • 3,177
  • 6
  • 19
  • 37
1

You can use GetType to get the type of the class.

List<Animal> lstA = new List<Animal>();
        lstA.Add(new Cat());
        lstA.Add(new Dog());
        foreach(Animal a in lstA)
        {
            Console.WriteLine("Type of {0}", a.GetType());
        }

abstract class Animal
{}
class Cat : Animal
{}
class Dog : Animal
{}
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58