4

My class structure is as follows:

public class Animal
{
    private int _animalId;

    public virtual int AnimalId
    {
        get { return _animalId; }
    }
}

public class Dog : Animal
{
    public override int AnimalId
    {
        get 
        { 
            if (Request.Params["New_Animal"] == "true")
                return -1;
            else
                return AnimalId;
        }
    }
}

I would like to override the AnimalId property as follows: if it is a new animal the id should be -1, but if we are updating an existing animal I would like to return the AnimalId from the base class.

This is an extremely simplified example, but I'm wondering if / how this can be done.

Thanks

full-stack
  • 553
  • 5
  • 20
  • 1
    `_animalId` should probably be protected and not private – maccettura Oct 10 '18 at 20:07
  • 3
    return base.AnimalId; – yW0K5o Oct 10 '18 at 20:08
  • When you say you want to update an existing animal, do you mean to retrieve it from a database? Or do you mean that after a property is changed, the animal is no longer new and so therefore you want it to no longer have an Id of -1? – Jonathan Walton Oct 10 '18 at 20:09
  • @JonathanWalton update as in retrieve the record from database and update the data, and new as in inserting a new record into the database – full-stack Oct 10 '18 at 20:13
  • it sounds a little bit like inheritance is not the correct approach for you. Are you counting the animals? sounds like you need a static variaable – Mong Zhu Oct 10 '18 at 20:13
  • @MongZhu as I stated in my question, this is an extremely simplified example, but I will look into it and see if that is a viable option. – full-stack Oct 10 '18 at 20:15
  • thanks @yW0K5o, `base.AnimalId` is what I needed. – full-stack Oct 10 '18 at 20:27
  • what is the inheritance relationship good for ? I don't understand the connection to the database records – Mong Zhu Oct 10 '18 at 20:28
  • My page must inherit from the parent because there are many other methods and properties that are used. Once I'm already inheriting why should I create my own independent static property which will be using a value from the parent page. – full-stack Oct 10 '18 at 20:32
  • ok now the picture gets clearer in my mind. Ok then my comment is useless. thanx for the clarification – Mong Zhu Oct 10 '18 at 20:36

2 Answers2

4

Use base.AnimalId

public class Animal
{
    private int _animalId;

    public virtual int AnimalId
    {
        get { return _animalId; }
    }
}

public class Dog : Animal
{
    public override int AnimalId
    {
        get 
        { 
            if (Request.Params["New_Animal"] == "true")
                return -1;
            else
                return base.AnimalId;
        }
    }
}
yW0K5o
  • 913
  • 1
  • 17
  • 32
0

You can make the animalId in animal private protected and in dog you can then return base.animalid in the property

juliushuck
  • 1,398
  • 1
  • 11
  • 25