While reading a little article on Javascript performance enhancements (sorry lost linky) I noticed a little trick whereby a closure redefined itself and I wondered whether this was possible in C#. Well, lo-and-behold, it is i.e.

Func<bool> isTrue = () =>{
      isTrue = () => return false;
      return true;
};

On executing this function on the first occurrence the value will return true, but thereafter will return false, this may be useless but it’s pretty interesting (to me anyway).

Now the Javascript example, that I previously read, used this technique to avoid unnecessary conditional lookups when retrieving the window scroll position (depending on if the browser was IE/FF/Chrome etc). In C# and equivalent (if not slightly unrealistic) example might be:

Func<Coords, Postcode> getCoords = pCode => {
    if(CoordinateProviderConst=="XService")
       getCoords =  pstCode => new XService().Coords(pstCode);
     else
        getCoords =  pstCode => new YService().Coords(pstCode);
     return getCoords(pCode);
};

Now please don’t take the above code as being at all sensible, it’s not, it’s just the best example I could think up quickly. What it does show is that this technique gives us the ability to have almost a state-pattern-type-thing at the function level.

That said, I’m really struggling to think up a sensible use case for this technique and the Javascript example, I read about, could have been handled several other ways that would mean that only the conditional lookup occurred once. So with that final thought, here ends my random musings…. still it was pretty interesting to find out that this was even possible, if not a bit useless.

Advertisements