.net - Unrecognized C# syntax -
let's have:
class foo { public int intpropertyinfoo { get; set; } public bar barpropertyina { get; set; } } class bar { public string stringpropertyinbar { get; set; } } then we'd instantiate foo object initializer:
public static void main(string[] args) { var foo = new foo { intpropertyinfoo = 123, barpropertyina = // ommiting new , type name - why compile? { stringpropertyinbar = "something" } }; } the syntax of initializing barpropertyina baffles me, because code compiles without warnings and, when run, throws nullreferenceexception. don't recognize syntax, seems have same effect when used field, rather property.
disassembling compiled code yields this:
.method public hidebysig static void main(string[] args) cil managed { .entrypoint // code size 34 (0x22) .maxstack 3 .locals init ([0] class test.foo foo) il_0000: nop il_0001: newobj instance void test.foo::.ctor() il_0006: dup il_0007: ldc.i4.s 123 il_0009: callvirt instance void test.foo::set_intpropertyinfoo(int32) il_000e: nop il_000f: dup il_0010: callvirt instance class test.bar test.foo::get_barpropertyina() il_0015: ldstr "something" il_001a: callvirt instance void test.bar::set_stringpropertyinbar(string) il_001f: nop il_0020: stloc.0 il_0021: ret } // end of method program::main which looks like:
public static void main(string[] args) { var foo = new foo { intpropertyinfoo = 123 }; foo.barpropertyina.stringpropertyinbar = "something"; } so supposed syntactic sugar initializing property's/field's members, provided property/field initialized in constructor?
yes, sort of shorthand initializing properties start empty rather null. .net collection properties example of this.
var cmd = new system.data.sqlclient.sqlcommand() { parameters = { new system.data.sqlclient.sqlparameter() { parametername = "@p1", value = "somvalue"} }, commandtext = "select 1 table1 value = @p1" }; it allows initialize values of read-only properties.
//compiles , works var message = new mailmessage { = { "test@stackoverflow.com" } }; message = new mailmessage { // won't compile: read-only = new mailaddresscollection { "test@stackoverflow.com" }, }; borrowed pretty verbatim article: http://www.codeducky.org/even-concise-c-object-initializers/
new-less initializer syntax allows make code bit more concise , use initialization syntax configuring read-only properties. indeed, since base class library , popular .net package classes follow empty on null pattern collection properties, can take advantage of new-less syntax them. finally, using new-less initialization means benefit leaving in place defaults object initialized with.
Comments
Post a Comment