Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 204
Aran Mulholland Avatar asked Jan 19 '10 00:01

Aran Mulholland


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


1 Answers

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.

like image 94
Anon. Avatar answered Oct 27 '22 01:10

Anon.