+ 2

( Need Help ) How to change the value of private member of base class from derived class ? thank you đŸ±

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { class Person { private int Age ; private string Name ; public string name { get{return Name;} set{Name = value; } } } class Student : Person { public Student(string nm) { Person.name = nm; } public void Speak() { Console.Write("Name: "+ Person.name); } } static void Main(string[] args) { Student s = new Student("Agus"); s.Speak(); } } }

9th May 2019, 2:40 AM
Putu Ekky Crisayoga
Putu Ekky Crisayoga - avatar
2 RĂ©ponses
+ 4
This is an BIG don't do in object orientated programming! One subject of SOLID is the Open Closed Principle, that means classes should be open for extension but closed to modification. So use methods to modify object states. Not doing this will lead to inconsistent object states and thus invalid application state. Another point: Get/Set are Anti-Pattern in OO. Use messages, not state in OO. And set of states are immutable so better use structs than objects. And please do not nest classes into the static Programm class! Nesting classes is only suitable for very special cases.
9th May 2019, 6:45 AM
Daniel Adam
Daniel Adam - avatar
+ 4
Add a protected method to set / get / check the private members of the base class for child classes. This is normal.
6th Oct 2020, 6:44 PM
Michail Getmanskiy
Michail Getmanskiy - avatar