A quick question about encapsulation and accessor in C#
vs Java
.
Is this code in C#
equivalent to the one in Java below?
C#:
class MyClass{
public string var1 {get; private set;}
public int var2 {get; private set;}
public MyClass(string aString, int anInt){
this.var1= aString;
this.var2=anInt;
}
}
java
//Java
class MyClass{
private String var1;
private int var2;
public MyClass(String aString, int anInt){
this.var1= aString;
this.var2=anInt;
}
public String getVar1(){
return this.var1;
}
public void setVar1(int anInt){
this.var1 = anInt;
}
public int getVar2(){
return this.var2;
}
public void setVar2(String aString){
this.var2 = aString;
}
}
I'm coming from the java
world, not sure about the accessor shortening in C#
.
No, in the C# code you've got private setters - in your Java code they're public.
The C# equivalent to the Java code would be:
public string Var1 { get; set; }
public int Var2 { get; set; }
(I've changed the names to follow .NET naming conventions - properties are PascalCased.)
See more on this question at Stackoverflow