Click here to Skip to main content
14,882,175 members
Please Sign up or sign in to vote.
1.44/5 (3 votes)
See more:
Below codes are exactly from book example. But still giving me errors. I couldn't figure out what is wrong. Book also gave the output: Baby is called: kitten and Baby is called: puppy. I have hard time understanding the interface, on top of that this book example is giving me error, any help will be very appreciated.

C#
{
    interface ILiveBirth
    {
        string BabyCalled();
    }
    class Animal { }
    class Cat : Animal, ILiveBirth
    {
        string ILiveBirth.BabyCalled()
        { return "kitten"; }
    }
    class Dog : Animal, ILiveBirth
    {
        string ILiveBirth.BabyCalled()
        { return "puppy"; }
    }
    class Bird : Animal
    { }

    class Program
    {
        static void Main()
        {
            Animal[] animalArray = new Animal[3];
            animalArray[0] = new Cat();
            animalArray[1] = new Bird();
            animalArray[2] = new Dog();
            foreach(Animal a in animalArray)
            {
                ILiveBirth b = a as ILiveBirth;
                if (b ! = null)
                Console.WriteLine("Baby is called:{0}", b.Babycalled());
            }
        }
    }
}
Posted
Comments
PIEBALDconsult 3-May-14 18:41pm
   
Looks OK, what's wrong?<br><br>
I do wonder why it uses explicit implementation though. http://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx

1 solution

Hi,

There are a couple of errors in the following lines of code:
C#
if (b ! = null)
Console.WriteLine("Baby is called:{0}", b.Babycalled());

1. Should be !=, not ! = (without a space).
2. Should be BabyCalled, not Babycalled (case sensitivity).

Correct version:
C#
if (b != null)
Console.WriteLine("Baby is called:{0}", b.BabyCalled());
   
v3
Comments
RalvarezHose 3-May-14 19:10pm
   
Thank you. There was a printing error in the book "! =" and error from my side "b.Babycalled."
Andrius Leonavicius 3-May-14 19:18pm
   
You're welcome. Please accept (and rate) my solution. Thank you.
RalvarezHose 3-May-14 20:38pm
   
Quick question. outputs:
Baby is called: kitten
Baby is called: puppy
Is because of the foreach loop correct?
Andrius Leonavicius 3-May-14 21:48pm
   
Well, not exactly (the loop is OK). Notice this statement: if (b != null) In the case of the "Bird", b is null. Take a look at the class Bird. This class doesn't implement the ILiveBirth interface...

Is it clearer now?
RalvarezHose 3-May-14 22:02pm
   
Okay got it thanks.
Andrius Leonavicius 3-May-14 22:05pm
   
I'm glad to hear it. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900