0

In c# how can one define a static method that is to implemented by all derived/implementing types? I know you cannot define a static method within an interface.

Basic premise is like this:

Say for example I have a base class of Organism. Derived types would be Human and Dog.

I want a method which can return to me say the number of legs that a given organism has. So Human would be 2, dog would be 4, etc.

I can make such a method an instance method, but it doesn't make much sense because its going to be the same method for all Dog types, and the same for all Human types, etc.

helpme
  • 1

3 Answers3

6

I dont think you are fully understanding OO. It makes perfect sense to make it an instance method.

What would happen if you have 2 dogs(one named lucky), and lucky gets hit by a car losing a leg? With your model the entire species of dogs just lost a leg?

But in a better model:

#psudo 
class Organism{
   public abstract void legs(){ return 0;}
}
class Dog : Organism{
   private int _legs;
   public int legs(){ return _legs; }
}

then lucky would just lose a leg.


Nix
  • 57,072
  • 29
  • 149
  • 198
  • Ahh, reminds me of my AP Physics class. Will E. Bounce is walking north across a two lane road at 2.4 meters per second. Each lane is 4 meters wide. A truck is moving eastward at 30 meters per second. If the truck is in the far lane 200 meters away, and doesn't merge, Will E. Bounce? – Scott Apr 28 '11 at 12:49
0

Make it an instance method. Using inheritance, your derived classes should implement their own versions that return the appropriate values.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0

Something like this.

abstract class Organism
{
    public abstract int NumberOfLegs();
}

abstract class Biped : Organism
{
    public sealed override int NumberOfLegs()
    {
        return 2;
    }
}


abstract class Quadroped : Organism
{
    public sealed override int NumberOfLegs()
    {
        return 4;
    }
}

class Humand : Biped
{

}



class Dog : Quadroped
{

}

But I'd be worried about using such a taxonomy and even more worried about baking in those kinds of assumptions. That said, one nice thing about statically typed languages is that when you do need to revisit a bad assumption, it forces you to look at all the code relying on that assumption... this is a good thing.

Rodrick Chapman
  • 5,437
  • 2
  • 31
  • 32