Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn an Animal instance into a Dog instance?

Say I have the following classes:

class Animal
{
    public long Id { get; set; }
    public string Name { get; set; }
}

class Dog:Animal
{
    public void sniffBum()
    {
        Console.WriteLine("sniff sniff sniff");
    }
}

If I have an instance of Animal, how do I cast it to a Dog? Something like this:

Animal a = new Animal();
if ( some logic to determine that this animal is a dog )
{
    Dog d = (Dog)a;
    d.sniffBum();
}

Essentially I can't use interfaces. I will always have an Animal object coming out of my database like that. Dog doesn't have any more parameters than Animal has, only new methods.

I could just create a new Dog object, and pass the values across, (or have a constructor that takes a type Animal), but this just seems messy.

like image 463
Crudler Avatar asked Apr 25 '13 12:04

Crudler


2 Answers

First create animal as a Dog then check if it is a Dog

Animal a = new Dog();
if (a is Dog )
{
   Dog d = (Dog)a;
   d.sniffBum();
}
like image 186
Mehmet Ataş Avatar answered Sep 29 '22 07:09

Mehmet Ataş


To check whether an object can be cast to a type use the is keyword.

Animal animal = new Dog();

if( animal is Dog)
{
    //your code
}
like image 36
Hossein Narimani Rad Avatar answered Sep 29 '22 07:09

Hossein Narimani Rad