Search code examples
c#propertiesprivate-methods

C# Private members visibility


We have a Student class in our business model. something struck me as strange, if we are manipulating one student from another student, the students private members are visible, why is this?

   class Program {
      static void Main(string[] args) {

         Student s1 = new Student();
         Student s2 = new Student();

         s1.SeePrivatePropertiesAndFields(s2);
      }
   }

   public class Student {

      private String _studentsPrivateField;

      public Student() {
         _studentsPrivateField = DateTime.Now.Ticks.ToString();
      }

      public void SeePrivatePropertiesAndFields(Student anotherStudent) {
         //this seems like these should be private, even from the same class as it is a different instantiation
         Console.WriteLine(anotherStudent._studentsPrivateField);
      }
   }

Can i have some thoughts on the design considerations/implications of this. It seems that you can't hide information from your siblings. Is there a way to mark a field or member as hidden from other instances of the same class?


Solution

  • There's an easy way to ensure this:

    Don't mess around with private members of other instances of the same class.

    Seriously - you're the one writing the Student code.