Question

Suppose I have the class hierarchy where number get set to a default value through constructor chaining, when creating instance of B. Since the value of _number should be default the property Number must be overridden such that the set accessor is removed.

abstract Class A
{
    public int Number
    {
        get
        {
            return _number
        }
        set
        {
            _number = value;
        }
     }
 }

Class B : Class A
{
    public int Number
    {
        get
        {
            return _number
        }
     }
 }
Was it helpful?

Solution

This is not possible as you want and for good reason.

You are actually breaking Liskov's Substitution Principle. Liskov's says

objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program

Since your base class has a public set so should your derived class.

Almost the same arguments that I made in Override Interface Method in another Interface can be applied here

Since you can pass in a derived class where ever the base class is required, what happens now if a user calls that set on the property?

Although newing the method might seem like a possible solution, but that is actually wrong since newing hides the base property and does not override it. It will still be accessible since you are not hiding the set part(you are only hiding the getter).

If you made the setter private in the base class the setter would not be visible publicly for either base or derived. This could however be an option if you are using constructor assignment as you are specifying.

OTHER TIPS

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B(10);

            // b.Number = 10; // Error here
        }
    }

    public abstract class A
    {
        public A() { }

        public A(int number)
        {
            Number = number;
        }

        private int _number;

        public virtual int Number
        {
            get
            {
                return _number;
            }
            private set
            {
                _number = value;
            }
        }
    }

    public class B : A
    {
        public B(int number)
            : base(number) { }

        public override int Number
        {
            get
            {
                return base.Number;
            }
        }
    }
}

May be something like

class B : A
{
    public new int Number //NEW
    {
        get
        {
            return _number; //NUMBER IS DEFINED IN (A)
        }
     }
 }

but this has a problem.

Even if this works correctly

B b = new B(); 
b.Number = 10; //COMPILER ERROR FOR READONLY PROPERTY 

this will compile correctly

A b = new B(); 
b.Number = 10; //NO ERROR
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top