Problem with Designer and using Events

Hello.

I'm trying to create a game component which has some properties that generate events, like this:

private float positionX;

[DefaultValue(0)]

public float PositionX

{

get { return positionX; }

set

{

positionX = value;

PositionChanged(new MainCharacterEventArgs(this));

}

}

"PositionChanged" is an event that I would like to generate everytime the character changes position... The problem is, when I use this Component with the designer, it always gives me this error:

Object reference not set to an instance of an object.
Hide

at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)

I assume it's because it's trying to generate the event with "this" which is not instanciated yet. What can I do Just don't use the designer Or is there a way around this



Answer this question

Problem with Designer and using Events

  • Jason D. Camp

    I think you have to check for null before calling events (in case there aren't any subscribers), like this:


    if (
    PositionChanged != null)
    PositionChanged(new MainCharacterEventArgs(this));




  • Kamii47

    Oh! How newbish of me. Thanks a lot!
  • Problem with Designer and using Events