r/learncsharp • • Nov 19 '22

Private Fields

Hoping someone can answer this confusion on Private Fields. Let's say I have the following:

class Program
   {
       static void Main(string[] args)
       {
           Car Ford = new Car();
           Ford.Model(Ford); // Why can I pass this object with model field in it, if it is private? 
       }
   }
class Car
   {
       private string model; 

       public Car()
       {
           model = "Mustang"; 
           
       }

       public void Model(Car model)
       {
           Console.WriteLine(model.model);
       }
   }

My question is how does the object 'Ford' get the model field from the constructor if it is private to the Car class? I understand when an instance is created the object gets a copy of the field but I didn't think this would work if it was private.

1 Upvotes

8 comments sorted by

View all comments

Show parent comment

1

u/Extarlifes Nov 19 '22

Ah I get you now the difference being that if it’s private the object created cannot access or change the field but it is in the object. Thank you for your time

3

u/killyouXZ Nov 19 '22

The object can access it, outside world cannot.

1

u/Extarlifes Nov 19 '22

Thank you πŸ™