Let's consider this example:
public class Cat
{
public virtual string Noise
{
get { return "Meow"; }
}
public Cat()
{
}
}
Cat
provides some basic cat-related stuff, such as a Noise
. By default, it is Meow
.
public class AngryCat : Cat
{
public AngryCat()
{
}
public override string Noise
{
get { return "Angry Meow"; }
}
public void Bite()
{
}
}
AngryCat
is a bit more angry and returns AngryMeow
instead.
public static class CatFactory
{
public static Cat GetCat()
{
return new AngryCat();
}
}
CatFactory
creates a new AngryCat
, using the base class Cat
as a type.
So far so good.
Now, I want to pet that Cat
.
static void Main(string[] args)
{
Cat animal = CatFactory.GetAnimal();
PetCat(animal);
Console.ReadLine();
}
public static void PetCat(Cat animal)
{
Console.WriteLine(animal.Noise);
}
The output is - as expected - Angry Meow
. However, I've got a specific case where this is not what I want.
I`ve got an API that - for the sake of the example - only consumes Cat
objects. It doesn't know about AngryCats
. It's not a .NET application so it doesn't know the type, but rather that a Cat
is related Meow
.
Now, the people using the library don't know about this restriction because it's not something they should know.
What I want to do is to actually downcast the AngryCat
to Cat
, so that the AngryCat
specific property and methods are removed.
Casting, such as Cat animal = CatFactory.GetAnimal();
doesn't work because, well, it's still a AngryCat
.
I found out that I can use JSON.NET to serialize the AngryCat
into a string and then deserialize that string into a Cat
, which does what I want. But that seems rather hacky.
Is there something built-in that can help me out (except for writing a copy constructor)?