Issue with using GetType() and typeof with with base/inherited classes.

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 Hierarcy (which stores all child classes in one table with a Discrimator column).

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 Method ——

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

—— Controller Method ——

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 works 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.

by mason240 via /r/csharp

Leave a Reply