Are both the below same?
Yes
If yes, then what's the point of this optimization?
I personally don't feel there is one, and I use the {} approach
For example - suppose I want to keep code readable and say have multiple lines of code in the get/set then I MUST use Sample 2 approach?
Yes. If you think about it, the way you'd normally write a multi line value-returning expression (enclose it in braces, put a return at the end) makes it 2 chars longer for the =>
public string Name{
get => {
if(x==y) return a;
return b;
}
}
public string Name{
get {
if(x==y) return a;
return b;
}
}
so there doesn't seem much point supporting it
What does an expression bodied property give you? Saves you a few bytes of not having to type return in the get. You don't save anything on the curly braces because you have to type =>
If you're going to have "simple get/set that just returns/sets a backing field" you can tidy the code down to just
public string Name{get;set;}
and skip the backing field part (use the property within the class to get/set the value)
If you're going to have a read only property and backing field you can:
public string Name => _name;
The other two options (in your question) are identical; pick whichever one you think looks tidier
If you're making a class that mostly holds data you can simplify your life by using a record:
public record SaleItem(string Name);
That's all you need to type, and it functions like the class you have there in terms of being a reference type and having an externally visible property Name. You add more props between the parentheses, and the compiler generates a constructor for you that looks the same:
var s = new SaleItem("socks");
As well as overriding equals and some other good stuff. See here