0

I am having an issue with getting the types of a class based on using GetType() and typeof(), the issue being that it isn't working.

I have base class of Content and inherited classes of Podcast and AudioBook.

I am using Code First and have a Table per Hierarchy (which stores all child classes in one table with a Discriminator column) to store all the Content entities.

I want to query the Content table by the Title column, and return a Content entity. Then, based on the type (Podcast, AudioBook) do some other things. However the type check isn't working.

Models

public abstract class Content
{ 
    public string Title { get; set; }
}

public class Podcast : Content
{

}

Repository

public Content FindContentByRoutingTitle(string routingTitle)
{
    var content = Context.ContentItems
    .FirstOrDefault(x => x.RoutingTitle == routingTitle);

    return content;
}

Controller

var content = _contentRepository.FindContentByRoutingTitle(title);

if (content.GetType() == typeof(Podcast))
{
    return RedirectToAction("Index", "Podcast", new { title = title });
}
else if (content.GetType() == typeof(Content))
{
    //just a check to see if equating with Content
    return RedirectToAction("Index", "Podcast", new { title = title });
}
else
{
    //if/else block always falls to here.
    return RedirectToAction("NotFound", "Home");
}

Is there something I am missing here? Thanks for your help.

Reference: Type Checking: typeof, GetType, or is?

Community
  • 1
  • 1
Mason240
  • 2,924
  • 3
  • 30
  • 46

1 Answers1

5

GetType() returns the actual class of the object so if you try to compare it to typeof(Content) you will get false. However If you want to check if the variable derives from a base class I recommend 2 options.

  • Option 1:

    if (content is Content)
    {
         //do code here
    }
  • Option 2:

    if (content.GetType().IsSubclassOf(typeof(Content)))
    {
     //do code here
    }
BetaVI
  • 86
  • 5