If I have a method that takes any object as a parameter I will like to create another object of the same type. In other words if I have an object of type Person I will like to cast or instantiate a new object of type person. If that object is an Animal in the other hand I will like to instantiate a new object from that class. All this without using an if or switch statement. let me show you what I mean
class Animal {
public virtual void Talk()
{
Console.WriteLine("-");
}
}
class Dog :Animal
{
public override Talk()
{
Console.WriteLine("Woof");
}
}
class Cat : Animal
{
public override void Talk()
{
Console.WriteLine("Miau");
}
}
public static void Main(String[] args)
{
Animal a = generateRandomAnimal();
Animal b; // I want to institate object b without needing an if statement or a switch
// I want to avoid this...
if (a is Dog)
b = new Dog();
else if (a is Cat)
b = new Cat();
else
b = new Animal();
// if I new what b would be a Cat in advance i know I could do :
b = (Cat)b;
// if am looking for something like
b=(a.GetType())b; // this gives a compile error
}
static Animal generateRandomAnimal()
{
switch (new Random().Next(1, 4))
{
case 1:
return new Animal();
case 2:
return new Dog();
default:
return new Cat();
}
}
Edit
Thanks to kprobst I ended up with:
class Person
{
public string Address { get; set; }
public string Name { get; set; }
}
class Animal
{
public virtual void Talk()
{
Console.WriteLine("-");
}
}
class Car
{
public int numberOfDoors { get; set; }
}
static object generateRandomObject()
{
switch (new Random().Next(1, 4))
{
case 1:
return new Person();
case 2:
return new Car();
default:
return new Animal();
}
}
public static void Main(String[] args)
{
object o = generateRandomObject();
object newObject; // i want new object to be of the same type as object o
if (o is Animal)
newObject = new Animal();
if (o is Person)
newObject = new Person();
if (o is Car)
newObject = new Car();
Type t = o.GetType();
var b = Activator.CreateInstance(t);
//.....etc
In my example not all objects inherited from the same class. It is the first time I see the a real benefit from the var keword. I know it is helpful but I just have use it to make my code smaller and more readable… but in this case it really helps out!
Something like this:
(didn’t actually test that)