Home > Back-end >  Auto-property vs property with a field
Auto-property vs property with a field

Time:09-28

Is there any difference between these two?

int a;
public int A
{
    get => a;
    set => a = value;
}
public int A { get; set; }

CodePudding user response:

public int A { get; set; }

is the exact same as saying:

private int _a;
public int A
{
    get => _a;
    set => _a = value;
}

Auto-properties are simply syntactic sugar for a private field, and public getters and setters. It allows you to access and mutate a field (as a property) without the boilerplate of getter and setter methods. We must always encapsulate our data, and properties aim to speed up the process of writing that out

If this was java, you would have something like:

private int a;

public void setA(int a){
    this.a = a;
}

public int getA(){
    return a;
}

When creating classes in java, it becomes extremely routine to define your getters, setters, hash code, and to string methods. Auto-props aim to take away a bit of the hassle. It just a quality-of-life bit of syntax for cleaner looking code.

Its also quite modular, take a look at the documentation to see how you can make for things like private setters, use init for immutability post-obj construction, etc

  • Related