roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

Passing dynamic type in constructor makes compiller skip Object initializer

Open horse315 opened this issue 11 years ago • 4 comments

Example:

    class Program
    {
        static void Main(string[] args)
        {
            NotWorks();
            Works();
        }

        public static void NotWorks()
        {
            var cc = new Cc(1, (dynamic)new object())
            {
                C = Guid.NewGuid()
            };
            Console.WriteLine(cc.C);
        }

        public static void Works()
        {
            var cc1 = new Cc(1)
            {
                C = Guid.NewGuid()
            };
            Console.WriteLine(cc1.C);
        }
    }

    public class Cc{

        public int A { get; set; }
        public dynamic B { get; set; }

        public Guid C { get; set; }

        public Cc(int a)
        {
            A = a;
        }

        public Cc(int a, dynamic b)
        {
            A = a;
            B = b;
        }
    }

Output:
> 00000000-0000-0000-0000-000000000000
> e3812288-9342-46a8-90af-1087488a30ff

horse315 avatar Apr 16 '15 09:04 horse315

csc2 compiller, .net 4.6 VS 2015

horse315 avatar Apr 16 '15 09:04 horse315

Does not happen (iow it works as expected) when calling it like:

  var cc = new Cc(1, new object())
  {
      C = Guid.NewGuid()
  };

Seems the cast to dynamic is causing the issue.

leppie avatar Apr 16 '15 10:04 leppie

@leppie, yes, it is. in IL code csc2.exe compiller does not insert this piece at all:

ldloc.1
call       valuetype [mscorlib]System.Guid [mscorlib]System.Guid::NewGuid()
callvirt   instance void Fw4._5TestApp.Cc::set_C(valuetype [mscorlib]System.Guid)

And csc.exe works fine.

horse315 avatar Apr 16 '15 10:04 horse315

@VSadov Please verify.

AlekseyTs avatar Apr 22 '15 22:04 AlekseyTs