+ 4
Auto-property vs public member
I am a Java programmer I would like to know the differences when auto-property and a public member are used . I think that have the same funcionality because both can be accessed from outside of the class.
7 odpowiedzi
+ 4
Auto properties are just easy syntacal ways of writing getters and setters.
int someInt;
public int SomeInt{get; set;}
This is equivalent to:
public int SomeInt{
get{ return someInt; }
set{ someInt = value; }
}
Which would be the same if written in Java as:
public int getSomeInt(){
return someInt;
}
public void setSomeInt(int newInt){
someInt = newInt;
}
However instead of writing get() you just write SomeInt and instead of writing set(int) you just write SomeInt = newValue.
My apologies if this didn't directly answer the question, I wasn't entirely sure what you meant.
Are you asking, why use a getter and setter over a public member?
If so, it's mainly for encapsulation. Java does the same thing anyway though, with getters and setters.
+ 1
From the outside they look the same. But a field is a field and a property is a property.
The property is the most advanced of the two options. If there is not a really good reason to choose a field, do choose the property.
If you ever want to implement a real setter, you can do without breaking the interface if you have an auto-property.
if you made it a field, you have to recompile every program that uses the class.
+ 1
don't you guys agree that sololearn should add a button for us to be able to fav. codes(besides saving),so that we can easily refer to (consult)any of our favorite codes from codeplayground in its original form.
0
In Auto properties the compiler generates an automatic private backing member for the publically declared member
class someClass
{
public string Name {get; set;}
}
is same as
class someClass
{
private string _name; // note _name (the actual compiler generated variable name may be different) is compiler generated and is not accessible at all.
public string Name
{
get{ return _name; }
set{ _name = value; }
}
}
Note if you use user defined private member in get, set method as in the example by @Rrestoring faith, then it is not auto implemented property. In that case you are generating property in a regular verbose way.
0
if you want to access data of a each method and set it's value then it's better to use auto property
0
If you want to be able to customize /control how your variable can be accessed and processed without affecting the actual code, then yes.
Access:
eg. get is public, set is private / protected
Process:
eg. return a changed value by get:
float Attack { get { return attack * multiplier; } }
- 1
haha