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.
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();
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With