Overriding fields or properties in subclasses

214,551

Solution 1

Of the three solutions only Option 1 is polymorphic.

Fields by themselves cannot be overridden. Which is exactly why Option 2 returns the new keyword warning.

The solution to the warning is not to append the “new” keyword, but to implement Option 1.

If you need your field to be polymorphic you need to wrap it in a Property.

Option 3 is OK if you don’t need polymorphic behavior. You should remember though, that when at runtime the property MyInt is accessed, the derived class has no control on the value returned. The base class by itself is capable of returning this value.

This is how a truly polymorphic implementation of your property might look, allowing the derived classes to be in control.

abstract class Parent
{
    abstract public int MyInt { get; }
}

class Father : Parent
{
    public override int MyInt
    {
        get { /* Apply formula "X" and return a value */ }
    }
}

class Mother : Parent
{
    public override int MyInt
    {
        get { /* Apply formula "Y" and return a value */ }
    }
}

Solution 2

Option 2 is a non-starter - you can't override fields, you can only hide them.

Personally, I'd go for option 1 every time. I try to keep fields private at all times. That's if you really need to be able to override the property at all, of course. Another option is to have a read-only property in the base class which is set from a constructor parameter:

abstract class Mother
{
    private readonly int myInt;
    public int MyInt { get { return myInt; } }

    protected Mother(int myInt)
    {
        this.myInt = myInt;
    }
}

class Daughter : Mother
{
    public Daughter() : base(1)
    {
    }
}

That's probably the most appropriate approach if the value doesn't change over the lifetime of the instance.

Solution 3

You could do this

class x
{
    private int _myInt;
    public virtual int myInt { get { return _myInt; } set { _myInt = value; } }
}

class y : x
{
    private int _myYInt;
    public override int myInt { get { return _myYInt; } set { _myYInt = value; } }
}

virtual lets you get a property a body that does something and still lets sub-classes override it.

Solution 4

option 2 is a bad idea. It will result in something called shadowing; Basically you have two different "MyInt" members, one in the mother, and the other in the daughter. The problem with this, is that methods that are implemented in the mother will reference the mother's "MyInt" while methods implemented in the daughter will reference the daughter's "MyInt". this can cause some serious readability issues, and confusion later down the line.

Personally, I think the best option is 3; because it provides a clear centralized value, and can be referenced internally by children without the hassle of defining their own fields -- which is the problem with option 1.

Solution 5

You could define something like this:

abstract class Father
{
    //Do you need it public?
    protected readonly int MyInt;
}

class Son : Father
{
    public Son()
    {
        MyInt = 1;
    }
}

By setting the value as readonly, it ensures that the value for that class remains unchanged for the lifetime of the object.

I suppose the next question is: why do you need it?

Share:
214,551

Related videos on Youtube

flytzen
Author by

flytzen

Updated on March 28, 2021

Comments

  • flytzen
    flytzen about 3 years

    I have an abstract base class and I want to declare a field or a property that will have a different value in each class that inherits from this parent class.

    I want to define it in the baseclass so I can reference it in a base class method - for example overriding ToString to say "This object is of type property/field". I have got three ways that I can see of doing this, but I was wondering - what is the best or accepted way of doing this? Newbie question, sorry.

    Option 1:
    Use an abstract Property and override it on the inherited classes. This benefits from being enforced (you have to override it) and it is clean. But, it feels slightly wrong to return a hard-code value rather than encapsulate a field and it is a few lines of code instead of just. I also have to declare a body for "set" but that is less important (and there is probably a way to avoid that which I am not aware of).

    abstract class Father
    {
        abstract public int MyInt { get; set;}
    }
    
    class Son : Father
    {
        public override int MyInt
        {
            get { return 1; }
            set { }
        }
    }
    

    Option 2
    I can declare a public field (or a protected field) and explicitly override it in the inherited class. The example below will give me a warning to use "new" and I can probably do that, but it feels wrong and it breaks the polymorphism, which was the whole point. Doesn't seem like a good idea...

    abstract class Mother
    {
        public int MyInt = 0;
    }
    
    class Daughter : Mother
    {
        public int MyInt = 1;
    }
    

    Option 3
    I can use a protected field and set the value in the constructor. This seems pretty tidy but relies on me ensuring the constructor always sets this and with multiple overloaded constructors there is always a chance some code path won't set the value.

    abstract class Aunt
    {
        protected int MyInt;
    }
    
    class Niece : Aunt
    {
        public Niece()
        {
            MyInt = 1;
        }
    }
    

    It's a bit of a theoretical question and I guess the answer has to be option 1 as it is the only safe option but I am just getting to grips with C# and wanted to ask this of people with more experience.

    • Navid Golforoushan
      Navid Golforoushan almost 5 years
      abstract public int MyInt { get; set;} => public abstract string IntentName { get; set;} :D
    • Servy
      Servy about 3 years
      @Čamo It's not appropriate to edit titles as you're doing. Tags are there to accomplish that.
    • Čamo
      Čamo about 3 years
      Language should be in title. Nobody has time to search and read little tags somewhere at the end of the question while needs to search tons of results. Thank you for understanding
    • Čamo
      Čamo about 3 years
      If language would be in the title it would not be in my search result for Java. Hope this to reasons make sense.
    • Servy
      Servy about 3 years
      @Čamo And yet your personal opinion on the matter is in strict opposition to the site's policy on the matter. Just because you want everyone to put their tags in the title doesn't make it appropriate. Tags are considered when searching, not just titles. Hope these reasons make sense and thanks for your understanding in not violating site rules going forward.
    • Čamo
      Čamo about 3 years
      May be the policy is wrong. What does not make sense on my comments? This is not about opinions it is about the truth.
    • Servy
      Servy about 3 years
      @Čamo If you want the policy changed the propose that the policy be changed, don't go around improperly editing questions. There are lots of lengthy discussions on the matter which you're free to read up on if you're interested in the explanations of the current policy, and which you should absolutely familiarize yourself with before proposing changing it.
    • Čamo
      Čamo about 3 years
      There is only one truth. The truth is this C# question is in my Java result. Never read the tags. Is could be useful for search engine but not for humans.
  • Winston Smith
    Winston Smith over 15 years
    Static is a poor choice of words since it implies the value is then shared between all instances of the class, which of course it isn't.
  • Peter - Reinstate Monica
    Peter - Reinstate Monica about 10 years
    As an aside, I really think the Father should apply formula "Y", and the Mother, logically, "X".
  • codingbiz
    codingbiz over 9 years
    Can we say this now not correct based on this msdn.microsoft.com/en-us/library/9fkccyh4.aspx The msdn article shows you can override properties
  • Jon Skeet
    Jon Skeet over 9 years
    @codingbiz: where does my answer talk about properties? Fields and properties are not the same thing.
  • Jon Skeet
    Jon Skeet over 9 years
    @codingbiz: (My answer now talks about properties, admittedly - but it never said you couldn't override them. It said - and says - that you can't override fields, which is still correct.)
  • Zimano
    Zimano over 6 years
    I feel like this is nice as an ad-hoc solution for prototyping or demoing.
  • Aaron Franke
    Aaron Franke over 5 years
    What if I wanted to supply a default implementation in Parent and have it not be abstract?
  • Ted Bigham
    Ted Bigham about 4 years
    @AaronFranke Make the signature: public virtual int MyInt { get; }
  • devinbost
    devinbost almost 4 years
    @Peter-ReinstateMonica That would be "genetic programming"