I know there are alot of questions allready to this topic. But I can't really seem to understand this whole delegate stuff. I'm kinda at a point where I just want it to work and move on. Everytime when I look at delegates I think to myself, there has to be a way to make this much easier to understand and do, but I can't seem to find it.
I have a FlowLayoutPanel that will be filled with a bunch of Panels. each of those panels needs to have a OnClick (or Click?) method to be attached to it.
So I went ahead and wrote (inside of the creator of my personal panel class):
IntDrawForm form = FindForm() as IntDrawForm;
Click += form.PointPanelClick;
And I ended up with the error message Delegate to an instance method cannot have null 'this'
when tried to create one my panels.
Yes, that will happen if FindForm()
returns either null
, or something that isn't an instance of IntDrawForm
. There's nothing particularly specific to delegates here - you'd get a similar result if you tried this as your second line:
form.CallSomeMethod();
(In that case it would be a NullReferenceException
.)
Given that the second line basically fails when form
is null
, you shouldn't use as
here - use a cast instead. That way, the first line will fail if you don't have an IntDrawForm
, and you'll get a more informative exception.
IntDrawForm form = (IntDrawForm) FindForm();
Now we can't tell why FindForm()
has returned either null
or a non-IntDrawForm
, but that's a different matter.
See more on this question at Stackoverflow