How to override an inherited class property in C#?

34,859

Solution 1

fly is not a property, it is a field. Fields are not overrideable. You can do this:

class bird {
    protected virtual string Fly {
        get {
            return "Yes, I can!";
        }
    }
    public string CanI() { return Fly; }
}

class penguin : bird {
    protected override string Fly {
        get {
            return "No, I can't!"; 
        }
    }
}

Note that I had to mark fly as protected.

But even better, I would do something like this:

abstract class Bird {
    public abstract bool CanFly { get; }
    public string SayCanFly() {
        if(CanFly) {
            return "Yes, I can!";
        }
        else {
            return "No, I can't!";
        }
    }
}

class Penguin : Bird {
    public override bool CanFly {
        get {
            return false;
        }
    }
}

class Eagle : Bird {
    public override bool CanFly {
        get {
            return true;
        }
    }
}

Solution 2

That is not a property in your example, it is a field. Try using a property, or simply marking fly as protected so it can be accessed in your subclass.

Solution 3

This code:

private virtual string fly = "Yes, I can!";

is creating a field, not a property. Also, in order to be virtual, your property must have access higher than 'private'. You probably want something like this:

public virtual string Fly
{
  get { return "Yes, I can!"; }
}
Share:
34,859

Related videos on Youtube

Rob
Author by

Rob

Updated on November 27, 2020

Comments

  • Rob
    Rob over 3 years

    I learned how to inherit methods by adding virtual to the method in the base class and override in the new class. But what do I do to inherit properties?

    class bird
    {
        private virtual string fly = "Yes, I can!";
        public string CanI() { return fly ; }
    }
    
    class penguin : bird
    {
        private override string fly = "No, I can't!";
    }
    

    This pops an error, saying that modifiers virtual/override should not be used here.

  • Luca
    Luca over 13 years
    I saw the downvote now. I really didn't want to downvote you answer. Spurious mouse click? Sorry for the incovenience, I removed it.
  • jason
    jason over 13 years
    @Luca: It's not an inconvenience, I just wanted to know if there was something wrong with my answer. Thank you for you coming back and commenting!