If you test a method like the following:
static void TestWithUnusedVariables()
{
var x = new Demo()
{
SomeProperty = "Hello World"
};
var y = new List<Demo>
{
new Demo() {
SomeProperty = "nada"
},
new Demo()
{
SomeProperty = "nix"
}
};
}
And decompile with ILSpy you might be thinking that object / collection intializers are not being detected:
private static void TestWithUnusedVariables()
{
Demo demo = new Demo();
demo.SomeProperty = "Hello World";
List<Demo> list = new List<Demo>();
list.Add(new Demo
{
SomeProperty = "nada"
});
list.Add(new Demo
{
SomeProperty = "nix"
});
}
Well, you are right. The reason being that the compilers sees that my user variables are not being used, thus optimizing the code by only keeping the compiler-generated ones, thus making it impossible for us to correctly detect the initializer.
However, if you use the variables
static void TestWithUsedVariables()
{
var x = new Demo()
{
SomeProperty = "Hello World"
};
var y = new List<Demo>
{
new Demo() {
SomeProperty = "nada"
},
new Demo()
{
SomeProperty = "nix"
}
};
x.SomeProperty = "noch was";
var z = y.Count();
}
ILSpy will correctly come up with proper decompiled code:
private static void TestWithUsedVariables()
{
Demo x = new Demo
{
SomeProperty = "Hello World"
};
List<Demo> y = new List<Demo>
{
new Demo
{
SomeProperty = "nada"
},
new Demo
{
SomeProperty = "nix"
}
};
x.SomeProperty = "noch was";
int z = y.Count<Demo>();
}
In the sense of a "variable being used" the decompilation also works for variables only used to pass back a value:
static Demo TestWithReturnValue()
{
return new Demo()
{
SomeProperty = "Hello World"
};
}
ILSpy output:
private static Demo TestWithReturnValue()
{
return new Demo
{
SomeProperty = "Hello World"
};
}
Bottom line: object and collection initializers are being properly decompiled if we can ascertain that it actually is one.