c# - Is a static readonly value type lifted in a closure? -


if have following:

static readonly timespan expiredafter = timespan.frommilliseconds(60000);  foreach (moduleinfo info in modulelist.where(i => datetime.now - i.lastpulsetime > expiredafter).toarray())     modulelist.remove(info); 

does expiredafter lifted or compiler know can access directly? more efficient write this:

static readonly timespan expiredafter = timespan.frommilliseconds(60000);  static bool hasexpired(moduleinfo i) { return datetime.now - i.lastpulsetime > expiredafter; }  foreach (moduleinfo info in modulelist.where(hasexpired).toarray())     modulelist.remove(info); 

a static (or matter, any) field can't possibly captured.

from language spec:

7.15.5 outer variables local variable, value parameter, or parameter array scope includes lambda-expression or anonymous-method-expression called outer variable of anonymous function. in instance function member of class, this value considered value parameter , outer variable of anonymous function contained within function member.

7.15.5.1 captured outer variables when outer variable referenced anonymous function, outer variable said have been captured anonymous function.

a static field never local variable, value parameter or parameter array.

that said, i've seen some strange corner cases compiler captures this without reason, doesn't seem 1 of those. verified decompiler both in case of instance , static enclosing method, code generated c# 4.0 compiler lambda pretty same 'manual' version... except compiler appears caching , reusing reference resulting delegate (in static field) only lambda case. counterintuitively make lambda way faster (and add less memory pressure) method-group way in case (over multiple executions of enclosing method)! you'll have benchmark both ways find out sure though...


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -