Search Results

Search found 8 results on 1 pages for 'controlflow'.

Page 1/1 | 1 

  • C# 4.0 'dynamic' and foreach statement

    - by ControlFlow
    Not long time before I've discovered, that new dynamic keyword doesn't work well with the C#'s foreach statement: using System; sealed class Foo { public struct FooEnumerator { int value; public bool MoveNext() { return true; } public int Current { get { return value++; } } } public FooEnumerator GetEnumerator() { return new FooEnumerator(); } static void Main() { foreach (int x in new Foo()) { Console.WriteLine(x); if (x >= 100) break; } foreach (int x in (dynamic)new Foo()) { // :) Console.WriteLine(x); if (x >= 100) break; } } } I've expected that iterating over the dynamic variable should work completely as if the type of collection variable is known at compile time. I've discovered that the second loop actually is looked like this when is compiled: foreach (object x in (IEnumerable) /* dynamic cast */ (object) new Foo()) { ... } and every access to the x variable results with the dynamic lookup/cast so C# ignores that I've specify the correct x's type in the foreach statement - that was a bit surprising for me... And also, C# compiler completely ignores that collection from dynamically typed variable may implements IEnumerable<T> interface! The full foreach statement behavior is described in the C# 4.0 specification 8.8.4 The foreach statement article. But... It's perfectly possible to implement the same behavior at runtime! It's possible to add an extra CSharpBinderFlags.ForEachCast flag, correct the emmited code to looks like: foreach (int x in (IEnumerable<int>) /* dynamic cast with the CSharpBinderFlags.ForEachCast flag */ (object) new Foo()) { ... } And add some extra logic to CSharpConvertBinder: Wrap IEnumerable collections and IEnumerator's to IEnumerable<T>/IEnumerator<T>. Wrap collections doesn't implementing Ienumerable<T>/IEnumerator<T> to implement this interfaces. So today foreach statement iterates over dynamic completely different from iterating over statically known collection variable and completely ignores the type information, specified by user. All that results with the different iteration behavior (IEnumarble<T>-implementing collections is being iterated as only IEnumerable-implementing) and more than 150x slowdown when iterating over dynamic. Simple fix will results a much better performance: foreach (int x in (IEnumerable<int>) dynamicVariable) { But why I should write code like this? It's very nicely to see that sometimes C# 4.0 dynamic works completely the same if the type will be known at compile-time, but it's very sadly to see that dynamic works completely different where IT CAN works the same as statically typed code. So my question is: why foreach over dynamic works different from foreach over anything else?

    Read the article

  • C# and F# lambda expressions code generation

    - by ControlFlow
    Let's look at the code, generated by F# for simple function: let map_add valueToAdd xs = xs |> Seq.map (fun x -> x + valueToAdd) The generated code for lambda expression (instance of F# functional value) will looks like this: [Serializable] internal class map_add@3 : FSharpFunc<int, int> { public int valueToAdd; internal map_add@3(int valueToAdd) { this.valueToAdd = valueToAdd; } public override int Invoke(int x) { return (x + this.valueToAdd); } } And look at nearly the same C# code: using System.Collections.Generic; using System.Linq; static class Program { static IEnumerable<int> SelectAdd(IEnumerable<int> source, int valueToAdd) { return source.Select(x => x + valueToAdd); } } And the generated code for the C# lambda expression: [CompilerGenerated] private sealed class <>c__DisplayClass1 { public int valueToAdd; public int <SelectAdd>b__0(int x) { return (x + this.valueToAdd); } } So I have some questions: Why does F#-generated class is not marked as sealed? Why does F#-generated class contains public fields since F# doesn't allows mutable closures? Why does F# generated class has the constructor? It may be perfectly initialized with the public fields... Why does C#-generated class is not marked as [Serializable]? Also classes generated for F# sequence expressions are also became [Serializable] and classes for C# iterators are not.

    Read the article

  • Is this an F# quotations bug?

    - by ControlFlow
    [<ReflectedDefinition>] let rec x = (fun() -> x + "abc") () The sample code with the recursive value above produces the following F# compiler error: error FS0432: [<ReflectedDefinition>] terms cannot contain uses of the prefix splice operator '%' I can't see any slicing operator usage in the code above, looks like a bug... :) Looks like this is the problem with the quotation via ReflectedDefinitionAttribute only, normal quotation works well: let quotation = <@ let rec x = (fun() -> x + "abc") () in x @> produces expected result with the hidden Lazy.create and Lazy.force usages: val quotation : Quotations.Expr<string> = LetRecursive ([(x, Lambda (unitVar, Application (Lambda (unitVar0, Call (None, String op_Addition[String,String,String](String, String), [Call (None, String Force[String](Lazy`1[System.String]), [x]), Value ("abc")])), Value (<null>)))), (x, Call (None, Lazy`1[String] Create[String](FSharpFunc`2[Unit,String]), [x])), (x, Call (None, String Force[String](Lazy`1[String]), [x]))], x) So the question is: is this an F# compiler bug or not?

    Read the article

  • System.Dynamic bug?

    - by ControlFlow
    While I playing with the C# 4.0 dynamic, I found strange things happening with the code like this: using System.Dynamic; sealed class Foo : DynamicObject { public override bool TryInvoke( InvokeBinder binder, object[] args, out object result) { result = new object(); return true; } static void Main() { dynamic foo = new Foo(); var t1 = foo(0); var t2 = foo(0); var t3 = foo(0); var t4 = foo(0); var t5 = foo(0); } } Ok, it works but... take a look at IntelliTrace window: So every invokation (and other operations too on dynamic object) causes throwing and catching strange exceptions twice! I understand, that sometimes exceptions mechanism may be used for optimizations, for example first call to dynamic may be performed to some stub delegate, that simply throws exception - this may be like a signal to dynamic binder to resolve an correct member and re-point delegate. Next call to the same delegate will be performed without any checks. But... behavior of the code above looks very strange. Maybe throwing and catching exceptions twice per any operation on DynamicObject - is a bug?

    Read the article

  • Parametrize the WHERE clause?

    - by ControlFlow
    Hi, stackoverflow! I'm need to write an stored procedure for SQL Server 2008 for performing some huge select query and I need filter it results with specifying filtering type via procedure's parameters (parameterize where clause). I found some solutions like this: create table Foo( id bigint, code char, name nvarchar(max)) go insert into Foo values (1,'a','aaa'), (2,'b','bbb'), (3,'c','ccc') go create procedure Bar @FilterType nvarchar(max), @FilterValue nvarchar(max) as begin select * from Foo as f where case @FilterType when 'by_id' then f.id when 'by_code' then f.code when 'by_name' then f.name end = case @FilterType when 'by_id' then cast(@FilterValue as bigint) when 'by_code' then cast(@FilterValue as char) when 'by_name' then @FilterValue end end go exec Bar 'by_id', '1'; exec Bar 'by_code', 'b'; exec Bar 'by_name', 'ccc'; But it doesn't work when the columns has different data types... It's possible to cast all the columns to nvarchar(max) and compare they as strings, but I think it will cause a performance degradation... Is it possible to parameterize where clause in stored procedure without using things like EXEC sp_executesql (dynamic SQL and etc.)?

    Read the article

  • C# Language Design: explicit interface implementation of an event

    - by ControlFlow
    Small question about C# language design :)) If I had an interface like this: interface IFoo { int Value { get; set; } } It's possible to explicitly implement such interface using C# 3.0 auto-implemented properties: sealed class Foo : IFoo { int IFoo.Value { get; set; } } But if I had an event in the interface: interface IFoo { event EventHandler Event; } And trying to explicitly implement it using field-like event: sealed class Foo : IFoo { event EventHandler IFoo.Event; } I will get the following compiler error: error CS0071: An explicit interface implementation of an event must use event accessor syntax I think that field-like events is the some kind of dualism for auto-implemented properties. So my question is: what is the design reason for such restriction done?

    Read the article

  • CLR 4.0 inlining policy? (maybe bug with MethodImplOptions.NoInlining)

    - by ControlFlow
    I've testing some new CLR 4.0 behavior in method inlining (cross-assembly inlining) and found some strage results: Assembly ClassLib.dll: using System.Diagnostics; using System; using System.Reflection; using System.Security; using System.Runtime.CompilerServices; namespace ClassLib { public static class A { static readonly MethodInfo GetExecuting = typeof(Assembly).GetMethod("GetExecutingAssembly"); public static Assembly Foo(out StackTrace stack) // 13 bytes { // explicit call to GetExecutingAssembly() stack = new StackTrace(); return Assembly.GetExecutingAssembly(); } public static Assembly Bar(out StackTrace stack) // 25 bytes { // reflection call to GetExecutingAssembly() stack = new StackTrace(); return (Assembly) GetExecuting.Invoke(null, null); } public static Assembly Baz(out StackTrace stack) // 9 bytes { stack = new StackTrace(); return null; } public static Assembly Bob(out StackTrace stack) // 13 bytes { // call of non-inlinable method! return SomeSecurityCriticalMethod(out stack); } [SecurityCritical, MethodImpl(MethodImplOptions.NoInlining)] static Assembly SomeSecurityCriticalMethod(out StackTrace stack) { stack = new StackTrace(); return Assembly.GetExecutingAssembly(); } } } Assembly ConsoleApp.exe using System; using ClassLib; using System.Diagnostics; class Program { static void Main() { Console.WriteLine("runtime: {0}", Environment.Version); StackTrace stack; Console.WriteLine("Foo: {0}\n{1}", A.Foo(out stack), stack); Console.WriteLine("Bar: {0}\n{1}", A.Bar(out stack), stack); Console.WriteLine("Baz: {0}\n{1}", A.Baz(out stack), stack); Console.WriteLine("Bob: {0}\n{1}", A.Bob(out stack), stack); } } Results: runtime: 4.0.30128.1 Foo: ClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at ClassLib.A.Foo(StackTrace& stack) at Program.Main() Bar: ClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at ClassLib.A.Bar(StackTrace& stack) at Program.Main() Baz: at Program.Main() Bob: ClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at Program.Main() So questions are: Why JIT does not inlined Foo and Bar calls as Baz does? They are lower than 32 bytes of IL and are good candidates for inlining. Why JIT inlined call of Bob and inner call of SomeSecurityCriticalMethod that is marked with the [MethodImpl(MethodImplOptions.NoInlining)] attribute? Why GetExecutingAssembly returns a valid assembly when is called by inlined Baz and SomeSecurityCriticalMethod methods? I've expect that it performs the stack walk to detect the executing assembly, but stack will contains only Program.Main() call and no methods of ClassLib assenbly, to ConsoleApp should be returned.

    Read the article

1