I'm going to modify your question slightly to provide a better comparison. In Java you commonly have public getters and private setters, with the constructor being the initializor[sic] of the variable, such as:
public class Person{
private String fName;
public Person (String name) {
setName(name);
}
private void setName(String someName){
fName = someName;
}
String getName(){
return fName;
}
}
With a user of the class only being able to retrieve the value after initialization through the constructor:
public class Example {
Person person = new Person("Fred");
System.out.println(person.getName()); // Allowed
System.out.println(person.fName); // Not allowed because fName is a local class variable
person.setName("Aaron"); // Not allowed because setName() is a local class method
}
Now this is where C# can become confusing, as instead of using Person.getName
you simply use the variable itself, however this variable can still be encapsulated. In Java you are taught that Class variables should be local (private) and should only be accessed with getters and setters. C# is essentially the same, but the syntax and logic is different. Rewriting my example in C# would be:
public class Person {
public String fName {get; private set;}
public Person(String name) {
this.fName = name;
}
}
public class Example {
Person person = new Person("Fred");
Console.WriteLine(person.fName); // This is allowed
person.fName = "Tony"; // Not allowed because setter is private
}
Now if you wanted to add logic to your getter and setter using the above conventions, you would need to introduce a local private variable, but the code in Example
and your Person constructor wouldn't change:
class Person {
private String _fName;
public String fName {
get { return _fName + ".addedText"; }
private set { _fName = value.ToLower(); }
}
public Person(String fName) {
this.fName = fName;
}
}
Now whether this is better or worse than Java is somewhat debatable, but from what I've seen your code is going to be out of place in C# if you do something like the below, although syntax wise it will work:
class Person2 {
private String fName;
public Person2(string fName) {
setFname(fName);
}
private void setFname(String fName) {
this.fName = fName.ToLower();
}
public String getFname() {
return this.fName+ ".addedText";
}
}