-3

i saw often people use this code like

interface IAnimal 
{
    void die();
}

class Cat : IAnimal 
{
    void die() { ... }
    void meow() { ... }
}

IAnimal anAnimal = new Cat();
Cat aCat= new Cat();

C# knows for sure anAnimal.die() works, because die() is defined in IAnimal. But it won't let you do anAnimal.meow() even though it's a Cat, whereas aCat can invoke both methods.

so tell me why & when we should write this kind of code

IAnimal anAnimal = new Cat();

what is the advantage ??

thanks

Thomas
  • 33,544
  • 126
  • 357
  • 626
  • 3
    This question appears to be off-topic because it is about broad, general programming concepts. This question belongs on http://programmers.stackexchange.com/ – Greg D Feb 20 '14 at 08:57
  • Kind of explained [here](http://stackoverflow.com/a/7211580/122005) – chridam Feb 20 '14 at 08:58
  • 2
    Downvote because the question is just copied and a little bit changed from the answer here http://stackoverflow.com/a/7211580/2655508 – Heslacher Feb 20 '14 at 09:02
  • 1
    @Heslacher, yes, there should be a reference to it in the question. As there is no reference, it looks more like an attempt to ask *popular* question. His last [question](http://stackoverflow.com/q/21902878/1997232) is also following same pattern. – Sinatr Feb 20 '14 at 09:30
  • By the way, .NET classes aren't variables as far as I know. – Sam Feb 20 '14 at 09:43
  • possible duplicate of [Interface instantiation vs class instantiation](http://stackoverflow.com/questions/7211571/interface-instantiation-vs-class-instantiation) – t1w Feb 20 '14 at 09:46

1 Answers1

0
  1. If anAnimal could also be assigned a different implementation of IAnimal, this is necessary.
  2. If the code that uses anAnimal isn't Cat-specific, this is probably a good idea to make the code more generic and reusable.
Sam
  • 40,644
  • 36
  • 176
  • 219