Question

I am creating a custom BindingSource and would like to persist a MethodInfo as a private field. The problem, in code:

public class MyBindingSource : BindingSource
{

    private MethodInfo MyMethod= null;

    protected override void OnBindingComplete(BindingCompleteEventArgs e)
    {
         this.MyMethod = GetMyMethod();
         //MyMethod is not null here
    }

    void UseMyMethod (object value)
    {
        MyMethod.Invoke(SomeObject, new object[] { value });
        //MyMethod is null here, exception thrown.
    }

}

I successfully store the MethodInfo, however, when i try to use it, it ends up being null. No special constructor is being called (overriding the field). OnBindingComplete is not called twice. Nothing seems to imply that something else is setting it to null.

Was it helpful?

Solution

Most probably you are accessing UseMethod before OnBindingComplete

But in any case, to prevent this, you can do something like this:

public class MyBindingSource : BindingSource
{
    private MethodInfo _myMethod = null;

    private MethodInfo MyMethod
    {
        get
        {
            if(_myMethod != null) return _myMethod;

            _myMethod = GetMyMethod();
            return _myMethod;
        }
    }

    protected override void OnBindingComplete(BindingCompleteEventArgs e)
    {
    }

    void UseMyMethod (object value)
    {
        MyMethod.Invoke(SomeObject, new object[] { value });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top