RE: Way to Lambda

One use of lambdas is to provide a method to a sub-routine that it can call if it needs something from the caller. I have implemented this pattern in a temporary caching class that I use sometimes but I think this example is more fun.

using System;
using System.Collections.Generic;
public class CowBell { }
public class BlueÖysterCult 
{
    public BlueÖysterCult()
    {
        var session = new JamSession<CowBell>();
        session.Jam(
            needs: () => session.TheCure.Count < 1000, 
            more: () => new CowBell());
    }
}
public class JamSession<T>
{
    public List<T> TheCure;
    public JamSession()
    {
        TheCure = new List<T>();
    }
    public void Jam(Func<Boolean> needs, Func<T> more)
    {
        while (needs())
        {
            TheCure.Add(more());
        }
    }
}

And if that is not a big enough of a yawn, here is a simple generic cache implementation.

    public class Cache<T> where T : class
    {
        private readonly Func<string, object> _get;
        private readonly Action<string, object> _set;
        private readonly Action<string> _clear;
        private readonly Func<string> _name;

        public Cache()
        {
            _get = (key) => HttpContext.Current.Cache[key];
            _set = (key, obj) => HttpContext.Current.Cache[key] = obj;
            _clear = (key) => HttpContext.Current.Cache.Remove(key);
            _name = () => typeof (T).FullName;
        }
        public T Item
        {
            get { return (T)_get(_name()); }
            private set
            {
                if (value == null) _clear(_name());
                else _set(_name(), value);    
            }
        }
        public T Get(Func<T> data)
        {
            return Item ?? (Item = data());
        }
        public void Clear()
        {
            Item = null;
        }
        public bool Exists()
        {
            return Item != null;
        }
    }


Leave a comment