9.10. Using Closures in C#
Problem
You want to associate a small amount of state with some behavior without going to the trouble of building a new class.
Solution
Use lambda expressions to implement closures. Closures can be defined as functions that capture the state of the environment that is in scope where they are declared. Put more simply, they are current state plus some behavior that can read and modify that state. Lambda expressions have the capacity to capture external variables and extend their lifetime, which makes closures possible in C#.
To show an example of this, you will build a quick reporting system that tracks sales personnel and their revenue production versus commissions. The closure behavior is that you can build one bit of code that does the commission calculations per quarter and works on every salesperson.
First, you have to define your sales personnel:
class SalesWeasel { #region CTOR public SalesWeasel( ) { } public SalesWeasel(string name, decimal annualQuota, decimal commissionRate) { this.Name = name; this.AnnualQuota = annualQuota; this.CommissionRate = commissionRate; } #endregion //CTOR #region Private Members decimal _commission; #endregion Private Members #region Properties public string Name { get; set; } public decimal AnnualQuota { get; set; } public decimal CommissionRate { get; set; } public decimal Commission { get { return _commission; } set { _commission = value; this.TotalCommission += _commission; } } public decimal TotalCommission {get; private ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access