What are the differences between these ways of setting a property?

34 Views Asked by At

What are the differences between these examples?

//example A
public class Product
{
    public string Name { get; set; } = "Limited Edition Item"
}
//example B
public class Product
{
    public string Name { get; set; } => "Limited Edition Item"
}
//example C
public class Product
{
    public string Name => "Limited Edition Item"
}

Is example A just a get set property with a default value? Is there a difference between example A and example B? Can example C be set or is it strictly a get?

1

There are 1 best solutions below

0
matt sharp On

When compiled, the get method is generated differently.

Example A will give you the same value every time you call it

Example B & C will give you a new value each time you call it.

Example C will not be settable and will return a new value each time you call it.

So:

public object Value { get; } = // This uses the same reference
public object Value => // This uses a new reference