Calling method 2 classes down from current method C#

Viewed 32

So I have a main class that has a list of objects.

List<Media> media = new List<Media>();

The media class is an abstract class. There is a class called Book that inherits from media. Following is an example of adding a book to the media list.

media.Add(new Book(mediaInfo[1], Convert.ToInt32(mediaInfo[2]), mediaInfo[3], summary));

mediaInfo is an array of values that gets passed into the constructor.

string[] mediaInfo = record.Split('|');

When the summary is passed into media it is encrypted. The book class contains a Decrypt() method that will decrypt it and that works fine. The problem is when I try to call it I get an error saying Decrypt is not in Media. So how do I call it. I tried this but I get the error.

foreach (Media m in media)
{
   if (m.Search(query))
   {

      if (m.GetType() == typeof(Book))
      {
          Console.WriteLine(m.ToString() + m.Decrypt());
      }
   }
}

I check if it is a Book so why can't it go down to Book to see if Decrypt is there. I cannot put decrypt into the Media class because there is also a song class that is not encypted.

2 Answers

I'd use pattern matching

foreach (Media m in media)
{
   if (m.Search(query))
   {

      if (m is Book b)
      {
          Console.WriteLine(b.ToString() + b.Decrypt());
      }
   }
}

Since m is of type Media (which doesn't contain Decrypt()), you'll need to cast m to Book:

Console.WriteLine(m.ToString() + ((Book)m).Decrypt());
Related