public static field vs public property with get for Functions
darkato42 opened this issue · comments
In Chapter07's solution, you had Remainder
defined as
public static Func<int, int, int> Remainder = (dividend, divisor)
=> dividend - ((dividend / divisor) * divisor);
why don't we have them as public property? what's the difference?
public static Func<Dividend, Divisor, int> Remainder
{
get { return (dividend, divisor) => dividend - (dividend / divisor) * divisor; }
}
In expression body:
public static Func<int, int, int> Remainder => (dividend, divisor)
=> dividend - ((dividend / divisor) * divisor);
In relation to your question "what's the difference", the answer is: exactly one character
Actually, you would need to add the readonly
modifier as well to make the field match the property:
public static readonly Func<int, int, int> Remainder = (dividend, divisor)
=> dividend - ((dividend / divisor) * divisor);
So now the difference is more than one character. 😉
Yes, that's correct.
And, since it's functional programming, you never want to reassign global variables, so that in real life you'd always want to specify readonly
, although in the book I probably omitted that, when it was not particularly relevant to the topic at hand, to make the examples less verbose.