C# class data members(fields or properties) can either be private or public or protected.
What if I want a private field for member methods use only and not to expose to the outside world?
I can continue to use a private field, without breaking encapsulation or anything right?
What I am not understanding is the two concepts: the data that we may need to expose to the outside world vs the data we may not need to do so (in the periphery of a class)..
What are these two types of data while talking about building a class?
In the below example, the private field 'name' is private to the class but is still gettable/settable to/by external world. Is the abstraction here then to 'not directly expose like 'here you go- have at it' but to add an indirect mechanism of access or update?? Is that the encapsulation we are talking about here when we talk about public fields vs public properties?
class Employee2
{
private string name = "Harry Potter";
private double salary = 100.0;
public string GetName()
{
return name;
}
public void SetName(string title, string fullName)
{
this.name = title + fullName;
}
public double Salary
{
get { return salary; }
}
}
class PrivateTest
{
static void Main()
{
Employee2 e = new Employee2();
// The data members are inaccessible (private), so
// they can't be accessed like this:
// string n = e.name;
// double s = e.salary;
// 'name' is indirectly accessed via method:
string n = e.GetName();
// 'salary' is indirectly accessed via property
double s = e.Salary;
}
}