I am trying to understand private fields in C#. Coming from a Java background, I am just a little confused.
Here is my class:
class Student
{
public int Age { get; set; }
public string Name { get; private set; }
public int x = 6;
public Student() // Empty constructor
{ }
public Student(int age, string name)
{
Age = age; // Work with Age as it is a field
Name = "John"; // OK: accessing a private setter
}
}
The auto-implemented properties Age
and Name
both can be accessed the same way the public x
can be accessed. I can write student.x
, just as I can write student.Age
.
I know that the compiler creates the private fields for Age
and Name
, but since I can access it the same as the x
, how is this private?
In Java, you have to call a public method that returns the private field, but with C#, it just seems like this defeats the purpose of a private field.
Basically, how does this benefit us at all? Why not just make everything public if we are going to set public setters and getters on Age
and Name
anyways? Logically, I just don't see the benefit or how this is actually private?
} set { }}` and then you can do something like `obj.X++;` whereas with methods you'd have to do `obj.SetX(obj.GetX()++);` so it gives you a better experience while still keeping the backing fields private so you can add any implementation you want while maintaining backwards compatibility.
– juharr Jun 07 '22 at 12:28