Bad idea. Normally, you should not have the index. You can get the reference to the button by type-casting the object
sender
to the type
System.Windows.Forms.Button
. Then you should use this reference.
But I understand if you really need to find out the index of this object in your array
MyButton
. You may really need it for some calculations. It's quite trivial operation to find it by the reference
sender
using, say,
System.Array.IndexOf
:
Array.IndexOf Method (Array, Object) (System)[
^].
Of course, it will work, and, for such a small array, even the miserable
time complexity of O(N) would not be a problem, from the practical point of view, but it would be the silliest way of doing things in general. A habit to search something with O(N) and a habit of searching of something which does not need to be searched my play an evil trick to you, eventually. You can avoid search. I would, for example, assigned the index of each button to the property
Button.Tag
, which can be any object. So, you can get this index from type-cast reference to
Button
taken from the
sender
in your event handler. The only little problem would be another type-cast operation, in addition to the one in the line above. You can perform this assignment in the same loop you used for adding
MyButtonClicked
handler to the invocation list of the event for all your instances.
There can be other ways. The biggest problem of your question is that you did not share the purpose of finding the index; if you did, the solution could be even simpler.
—SA