implicit-typing

Why can't an anonymous method be assigned to var?

[亡魂溺海] 提交于 2019-11-26 14:58:15
I have the following code: Func<string, bool> comparer = delegate(string value) { return value != "0"; }; However, the following does not compile: var comparer = delegate(string value) { return value != "0"; }; Why can't the compiler figure out it is a Func<string, bool> ? It takes one string parameter, and returns a boolean. Instead, it gives me the error: Cannot assign anonymous method to an implicitly-typed local variable. I have one guess and that is if the var version compiled , it would lack consistency if I had the following: var comparer = delegate(string arg1, string arg2, string arg3

Implicit typing; why just local variables?

我的未来我决定 提交于 2019-11-26 14:47:36
Does anyone know or care to speculate why implicit typing is limited to local variables? var thingy = new Foo(); But why not... var getFoo() { return new Foo(); } Eric Lippert did an entire blog post on the subject. http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx In summary, the main problem is that it would have required a major re-architecture of the C# compiler to do so. Declarations are currently processed in a single pass manner. This would require multiple passes because of the ability to form cycles between inferred variables. VB.net has roughly the same

Why can&#39;t an anonymous method be assigned to var?

半世苍凉 提交于 2019-11-26 04:06:46
问题 I have the following code: Func<string, bool> comparer = delegate(string value) { return value != \"0\"; }; However, the following does not compile: var comparer = delegate(string value) { return value != \"0\"; }; Why can\'t the compiler figure out it is a Func<string, bool> ? It takes one string parameter, and returns a boolean. Instead, it gives me the error: Cannot assign anonymous method to an implicitly-typed local variable. I have one guess and that is if the var version compiled , it

Implicit typing; why just local variables?

半世苍凉 提交于 2019-11-26 04:01:59
问题 Does anyone know or care to speculate why implicit typing is limited to local variables? var thingy = new Foo(); But why not... var getFoo() { return new Foo(); } 回答1: Eric Lippert did an entire blog post on the subject. http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx In summary, the main problem is that it would have required a major re-architecture of the C# compiler to do so. Declarations are currently processed in a single pass manner. This would require