Observe the following…
//pattern 1
public class Cheesesteak
{
public string bread {get; private set}
public string cheese {get; private set}
public Cheesesteak()
{
bread = "Amoroso";
cheese = "Cheez Whiz";
}
}
//pattern 2
public class Cheesesteak
{
public string bread
{
get {return bread;}
set
{
bread = "Amoroso";
}
}
public string cheese
{
get {return cheese;}
set
{
cheese = "Cheez Whiz";
}
}
public Cheesesteak() {}
}
This is a curiosity question. 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? My initial guess is pattern 1 is shorter, but less efficient during compile.
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 aStackOverflowException). Also note that trying to retrieve the value in your code will cause aStackOverflowException, and the property getter returns the property and not a backing field value.You were likely thinking of this:
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.
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:
Breadshould always return"Amoroso"), you can just make the property have a getter and no setter: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.