I have a parent class which 2 other classes inherit from. All of the instance variables are inherited from the parent class, and I want to write one method which can accept either of the subclasses as a parameter (without overloading the method if possible).

public class Project
{
static void main()
{

}

static void GetPetName(Dog d) // I want this to be able to accept
//cat as an alternate parameter
{
return d.Name;
}

}


class Pet
{
public Pet(){}
public int PetAge;
public string Name;
}

class Dog : Pet
{
public Dog() : base()
{
}
}

class Cat : Pet
{
public Cat() : base()
{

}
}

Have the method accept a parameter of type Pet rather than of type Dog or Cat. With Name and Age being properties of the base class rather than the derived types, you will be able to access them just fine within the method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.