LukeP
LukeP

Reputation: 1605

Find TypeOf Child class when casted as Parent

I have a Partial View that I want be able to use with several different models. Is there any way to find out what the Child class of an object is when it is being passed in as its parent?

For example:

Model:

public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }

Controller:

public class AnimalActionController : Controller
{
    public ActionResult MakeAnimalSound(Animal animal)
    {
       if (animal is Dog)
       {
         return PartialView("~/Views/_AnimalActionView.cshtml", new{sound="Woof"});
       }
       if (animal is Cat)
       {
         return PartialView("~/Views/_AnimalActionView.cshtml", new{sound="Meow"});
       }
    }
}

Parent View of Dog page:

@model Test.Models.Dog
@Html.Action("MakeAnimalSound", "AnimalAction", new { Model })

Right now if I were to do something like this example the if statements in the Controller only see animal as Animal and not as Dog or Cat which it originally was.

Anyone know how to do this? I feel like it should be simple.

Upvotes: 2

Views: 2280

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

A better choice for this would be to do something like this. Testing class types is a poor design and considered a code smell in most cases (sometimes it's necessary, but there's usually other ways to accomplish what you want without it):

public class Animal
{
     public virtual Sound {get;}
}
public class Dog : Animal
{
     public override Sound {get {return "Woof";}}
}
public class Cat : Animal
{
     public override Sound {get {return "Meow";}}
}

public ActionResult MakeAnimalSound(Animal animal)
{
   return PartialView("~/Views/_AnimalActionView.cshtml", new{sound=animal.Sound});
}

Upvotes: 3

Steve
Steve

Reputation: 6444

If you call the object's GetType() method, you will get an object that will tell you everything you need to know. See the MSDN page on System.Type.

The following program outputs Child.

internal class Parent {
    private string Something { get; set; }
}

internal class Child : Parent {
    private int SomethingElse { get; set; }
}

internal class Program {

    private static void Main(string[] args) {
        Parent reallyChild = new Child();
        Console.WriteLine(reallyChild.GetType().Name);
        Console.ReadLine();
    }
}

Upvotes: 2

Related Questions