Is there any advantage or particular reason that you would set the variables in the definition of the "set" versus declaring them in the constructor?
No, and in fact, this is probably not what you want at all. This will make it impossible to set "break" or "cheese", as any call, such as bread = "rye";
, would set it to "Amoroso" (if it worked, but will cause a StackOverflowException
). Also note that trying to retrieve the value in your code will cause a StackOverflowException
, and the property getter returns the property and not a backing field value.
You were likely thinking of this:
public class Cheesesteak
{
private string bread = "Amoroso";
public string Bread
{
get {return bread;}
set
{
bread = value;
}
}
// ...
The only advantage here is you're setting the "default" value where the field is defined, which can help with maintainability or readability in some cases, and even potentially eliminate the need for a defined constructor, which might reduce the overall length of code.
My initial guess is pattern 1 is shorter, but less efficient during compile.
In general, setting the fields inline vs. setting them in a constructor does not make this less efficient. The compiler will cause the type's actual constructor to set the fields first then run the constructor code, so both versions end up (for practical purposes) the same in terms of the compiled IL. This isn't a matter of efficiency, but rather of code readability and maintainability.
Note that, if you wanted the property to always be a constant (ie: Bread
should always return "Amoroso"
), you can just make the property have a getter and no setter:
public string Bread { get { return "Amoroso"; } }
I suspect this is not the case, but I thought I'd mention it as an option just in case it's what you intended.