TheLastGIS
TheLastGIS

Reputation: 434

Class inherits from interface with extra property causes error

I understand that interfaces don't allow fields. But why can't the class that implements the interface have a property/field. I have tried researching the cause of this, but to no avail. Could someone point me to a resource that can help me.

Can classes only implement the method they inherit from the interface and nothing else?

Here is my code:

using System;

interface IDog
{
    void Bark();
}

class Dog : IDog
{
    public int numberOfLegs = 24;
    public void Bark()
    {
        Console.WriteLine("Woof!");
    }
}

class Program
{
    static void Main()
    {
        IDog Fido = new Dog();
        Fido.Bark();
        Console.WriteLine("Fido has {0} legs", Fido.numberOfLegs);
    }
}

I get the error:

'IDog' does not contain a definition for 'numberOfLegs' and no extension method 'numberOfLegs' accepting a first argument of type 'IDog' could be found (are you missing a using directive or an assembly reference?)

Upvotes: 0

Views: 103

Answers (3)

Alexei Levenkov
Alexei Levenkov

Reputation: 100517

Interfaces can't have fields but they can have properties.

So to fix your issue where IDog does not have numberOfLegs field/property you can move it to interface:

interface IDog
{
    void Bark();
    int NumberOfLegs {get;}
}

class Dog : IDog
{
    public int NumberOfLegs {get {return 24;}}

    public void Bark()
    {
        Console.WriteLine("Woof!");
    }
}

Alternatively you can use Dog instead of IDog in your code...

Dog fido = new Dog();
Console.WriteLine("Fido has {0} legs", fido.NumberOfLegs);

Or even cast interface to class, but that will defeat creation of the interface.

IDog fido = new Dog();
Console.WriteLine("Fido has {0} legs", ((Dog)fido).NumberOfLegs);

Upvotes: 1

Mark Wade
Mark Wade

Reputation: 527

Your Fido variable references a Dog instance but is still of type IDog.

Change the first line of Main() to Dog Fido = new Dog(); or var Fido = new Dog();

The first part of the error is relevant here - 'IDog' does not contain a definition for 'numberOfLegs'. The part about extension methods doesn't apply, but will make sense when you learn extension methods (if you haven't).

Upvotes: 1

SLaks
SLaks

Reputation: 887195

Fido is declared to be of type IDog.

As the error clearly tells you, you cannot use a member that does not exist on the variable's compile-time type.

If you want to use a member declared by a derived type, you must change the variable to be of the derived type.

Upvotes: 2

Related Questions