roslyn
roslyn copied to clipboard
Passing dynamic type in constructor makes compiller skip Object initializer
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
csc2 compiller, .net 4.6 VS 2015
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, 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.
@VSadov Please verify.