I have a base class with has x amount of properties, I then have derived classes with more properties. How do I process the common fields in a method and then send the object to another method which can process its additional properties?
Example:
public Interface IAnimal {
int NoOfFeet;
}
class Animal: IAnimal {
int NoOfFeet {get;set;}
}
class Elephant: Animal {
bool hasTrunk {get;set;}
}
class Dog:Animal {
string canBark {get;set;}
}
Method1(IAnimal a) {
//process NoOfFeet ...
//process fields for derived type
DoSomething(IAnimal a)
}
DoSomething(Elephant e) {
//process trunk
}
DoSomething(Dog d) {
//process canbark
}
It sounds like you basically want overload resolution at execution time. (I'm assuming you can't introduce a virtual method to do the right thing, and implement it in each class. That would be the cleanest way if it's reasonable for the implementations to know what you're doing with them, but that's not always the case.) The simplest way of achieving that is using dynamic
, as introduced in C# 4:
public void Method(IAnimal animal)
{
// We don't want to call Handle with a null reference,
// or we'd get an exception to due overload ambiguity
if (animal == null)
{
throw new ArgumentNullException("animal");
}
// Do things with just the IAnimal properties
Handle((dynamic) animal);
}
private void Handle(Dog dog)
{
...
}
private void Handle(Elephant elephant)
{
...
}
private void Handle(object fallback)
{
// This method will be called if none of the other overloads
// is applicable, e.g. if a "new" implementation is provided
}
See more on this question at Stackoverflow