Friday 15 March 2013

c# - No error when looping over the array of a bounds? -


I found out that an error should be generated because the array is out of range, but instead it behaves weird . When I step on it, it stops after 4 loops and does not add control. How can it happen, no error or compiler warnings or nothing?

  panel [] panel = new panel [4]; Label [label] = new label [4]; Private Zero Form 1_load (Object Sender, EventArgse E) {For (XX = 0; X; LT; 20; X ++) {Label [x] = New Label {Name = x.ToString ("00"), BackAllore = Color.blue, text = "test"}; Panel [x] = new panel {name = x.ToString ("00"), backallore = color. Blue}; } TableLayoutPanel1.Controls.AddRange (label); TableLayoutPanel2.Controls.AddRange (panel); }    

If you wrap the code in try-hold, you will see threw Exception is my guess that an exception is thrown away and swallowed by the form when there is no attempt to catch anything.

  Zero form1_load (object sender, eventArgse E) {try (for int x = 0; x & lt; 20; x ++) {label [x] = new label {name = X.ToString ("00"), backallore = color. Blue, text = "test"}; Panel [x] = new panel {name = x.ToString ("00"), backallore = color. Blue}; } this. Control. AddRange (label); This.Controls.AddRange (panel); } Hold (exception before) {this.Text = ex.Message; }}   

In addition, as noted by commentators, the compiler does not check compile-time array limits.

EDITING: Extra Note, only when needed for this form in the load event handler. If this code is somewhere else, then it breaks when debugging normally (your visual studio believes that CLR is set to break exceptions).

More about this problem from Great Hans Pacecent:

And drilling through the answer ends on this blog post:

No comments:

Post a Comment