The Can Derived class hides accessors - what's wrong with the code below

I'm trying to hide accessors in a derived class, is it really? My system did not respond.

class BaseCS
  {
      private string name;

      public string Name
      {
          get { return name; }
          set { name = "Base " + value; }
      }    
  }

  class DerivedCS : BaseCS
  {
      public new string Name
      {
          set { Name = "Der " + value; }
          get { return Name; }
      }
  }

public static void Main()
        {
            BaseCS one = new DerivedCS();

            one.Name = "One";

            Console.WriteLine("Name of object one is {0} ", one.Name);


            ((BaseCS)one).Name = "On1";
            Console.WriteLine("Name of object one is {0} ", one.Name);
        }

Should I expect a conclusion

Name of object one is Base Der One
Name of object one is Base On1
+3
source share
2 answers
  • This code:

    public new string Name
    {
        set { Name = "Der " + value; }
        get { return Name; }
    }
    

    will lead to a stack overflow, since Namein getters and setters it will refer to Namein DerivedCS, not to BaseCS. Namethe property will call itself forever until it fails. You need to use base.Name.

  • What you probably want is polymorphism. You must make the property virtualand overridesetter in the derived class.

    If you do not use virtual properties, the following object will not behave the way you want:

    BaseCS one = new DerivedCS();
    one.Name = "name"; // base implementation is called
    
  • . :

    var a = new A();
    a.Foo = "bar";
    Debig.Assert(a.Foo == "bar");
    
+2

    class BaseCS
    {
        private string name;

        public virtual string Name
        {
            get { return name; }
            set { name = "Base " + value; }
        }

    }

    class DerivedCS : BaseCS
    {
        public override string Name
        {
            set { base.Name = "Der " + value; }
            get { return base.Name; }
        }
    }

 class BaseCS
    {
        private string name;

        public string Name
        {
            get { return name; }
        set { name = "Base " + value; }
    }

}

class DerivedCS : BaseCS
{
    public new  string Name
    {
        set { base.Name = "Der " + value; }
        get { return base.Name; }
    }
}

now you should create the object as the derived type to get your expected result

     DerivedCS one = new DerivedCS();
0

All Articles