   Could someone tell me a good use for Inheritance and Polymorphism in C#?
  Its a subject that Im having the hardest time understanding..for example, if I have a class Animal, and from it a derived class Dog I could use bothDog d1 = new Dog();ANDAnimal d1 = new Dog();now whats the difference, and I would really like to hear some practical examples of inheritance and polymorphism, please =)   
  Polymorphism is all about dynamically creating object types. Say you have a program that asks the user what type of pet he owns. You could then create either a dog object or a cat object depending on the user's choice. It's not something that's known at compile time. Along with that, you could traverse an array of animal objects in a loop. This wouldn't be possible without polymorphism (I.E. you couldn't store dogs, cats, and birds in a single array).   ;  Pseudo Code:Weapon CurrentWeapons[2];CurrentWeapons[0] = new Sword();CurrentWeapons[1] = new Gun();if( UserPressedKey_A )    CurrentWeapons[0].causeDamage();if( UserPressedKey_Z )    CurrentWeapons[1].causeDamage();As you see, it's a generic way to treat all kinds of weapons with the same interface, making it easy to read for the programmer and implement new types.Whatever happens inside causeDamage() is different for the sword and gun.Also probably the Gun and Sword may have common propierties (that whill be in the base class, Weapon) which reduce code duplication.You can copy-paste your code and say code duplication isn't much a problem. But when you found that the original code has a bug... well then you will have thousands of copy-paste everywhere to fix the bug. And if you forgot one spot, the bug will still be there. In other words: "argh"If you want later to create a new weapon, i.e. a staff, you implement a new derived class but you won't need to modify any of the existing code.This helps modularity, which means you later "plug" new implementations without modyfing the original code.Emulators (PCSX2, Project64) use base clases that DLLs have to derive from, that's how the "Plug in" works.When your code is modular, it usually means it's more independent and any problem can isolated quickly (because you can, among other things, plug "in and out" an interface easily, and see if the error persists)Polymorphism can also be used for code refactoring when you have multiple conditionals. Code becomes more readable and modular again.Well, there is more to say, but this is a quick introduction.CheresDark Sylinc   ;  alright thank you, both of you for the example and explanations. You have helped me to further understand this subject =P   ;  1) This is a design concept; the fact that you're using C# matters little.Quote:for example, if I have a class Animal, and from it a derived class Dog I could use bothDog d1 = new Dog();ANDAnimal d1 = new Dog();Yes.Quote:now whats the differenceIn the assignment, quite little. The point of polymorphism is that you can assign the Dog to an Animal variable.2) That means you can pass the Dog to a function that accepts an Animal.3) That means you can put the Dog in a container of Animals (zoo?).In these ways, you "forget" that the Animal is a Dog. But the object doesn't forget. Let's consider a little fragment of code (keep in mind that I don't actually know C# formally):public static void zomg_dinnertime(System.Collections.Generic.IList<Animal> zoo) {  for (Animal a: zoo) {    a.makeNoise();    // a.wagTail(); <-- doesn't compile.  }}Say we make an IList of Animals of some sort (there's actually another example of polymorphism, there; there are different kinds of containers, and this function should work with several different kinds), and put some Dogs in it, and pass it to the function.So the function goes through and grabs each animal in the list in turn, and asks it to makeNoise. When it gets to a Dog, the Dog will bark, because that's how Dogs make noise. But even if we only put Dogs in our container, the function can't ask the Animals to wagTail() - because all the function knows ahead of time is that it will receive Animals, and not all Animals have a tail to wag (it's not part of the Animal interface).The benefit we get from the polymorphism is that we can write this code, and we don't have to write the check to see what kind of Animal we have. That is, we don't look at the Animal and go "oh, are you an Aardvark? No? Okay, are you a Bird? No? Okay, are you a Cat? No? Okay, are you a Dog? Ah, you're a Dog. Okay, then bark()." We leave it up to the Animal to decide what kind of noise it makes - as we should.Quote:and I would really like to hear some practical examples of inheritance and polymorphism, please =)They're all around you.Polymorphism is the general concept. Inheritance is one way to acheive subtyping (i.e., making the statement in your code that "X is just a specific kind of Y, so everything that's an X is also a Y"), and polymorphism on subtypes is the kind of polymorphism most people think of immediately.The other kind is polymorphism on interface, where you don't really care what types are related, you just care what a given object claims it can do. This can be done in a few different ways.C++ does it with templates: basically, an object "can do" something if it has a function with the name that's requested (which can be dangerous: a Boss and a Gun can both fire()), but the code is generated ahead of time, per-type (this is tricky: the program has to figure out ahead of time what types are ever used for calling the function, and generate code for them). Actually, that whole description is a bit of a simplification, but probably good enough for a general understanding.C# does it basically through generics (like the IList<Animal>; there is no "base" IList through which those types are related, but they all provide related interfaces: an IList of Integers lets you add and remove Integers, and an IList of Animals lets you add and remove Animals) and interface specifications (implementing an interface is like inheriting from a class, except that the interface doesn't contain any data or implementation code; it just declares the functionality).Python does it through "duck typing", which in turn uses "reflection": objects actually remember the names of their functions, and when you call a method on an object, the object actually looks up the name in its own __dict__, and calls the corresponding function (or raises an AttributeError if it isn't there). (In a C++ program, the only place the variable names are guaranteed to exist is in the actual source code - unless you explicitly put them somewhere.)   ;  FWIW, a C# version of Zahlman's code would bepublic static void zomg_dinnertime(IEnumerable<Animal> zoo) {  foreach (Animal a in zoo) {    a.makeNoise();    // a.wagTail(); <-- doesn't compile.  }};Quote:Python does it through "duck typing", which in turn uses "reflection": objects actually remember the names of their functions, and when you call a method on an object, the object actually looks up the name in its own __dict__, and calls the corresponding function (or raises an AttributeError if it isn't there). (In a C++ program, the only place the variable names are guaranteed to exist is in the actual source code - unless you explicitly put them somewhere.)I don't know anything about Python but does that mean that you can do something like this:Animal animals[2];animals[0] = new Dog();animals[1] = new Cat();animals[0].wagTail();animals[1].climbTree();i.e access each subclasses specific methods without casting?It would be pretty nice if you can because that's the way I always thought polymorphism worked in C++, C# but then discovered it didn't.   ;  AFAIK yes. Python is dynamically typed. You can write code like this:class Animal:def makeNoise(self):print "..."class Dog(Animal):def wagTail(self):print "wag"def makeNoise(self):print "woof"class Cat(Animal):def climbTree(self):print "climbing"def makeNoise(self):print "meow"animals = [Dog(), Cat()]animals[0].wagTail();animals[1].climbTree();for animal in animals:animal.makeNoise()(Disclaimer: I don't actually use Python, hence the ugly hack of including a dummy function in Animal to get around a syntax error it gave me.)But the code there runs, doing what you might expect.The downside of dynamic typing is that if you were to put a Truck object in the "animals" list, you won't get an error until you do something a truck cannot support. This means that errors that would have been caught earlier are now delayed until runtime (hopefully you'll catch them before you ship!).Its a tradeoff, additional flexibility but its a source of other problems.   ;  I'm guessing you wanted:class Animal:passThough in this case there doesn't seem to be any need for the Animal base class at all.   ;Quote:Original post by SiCraneI'm guessing you wanted:class Animal:passThough in this case there doesn't seem to be any need for the Animal base class at all.Very true. I was just translating the code, I wasn't really thinking. Its late here [embarrass]   