Method call if not null in C#

后端 未结 11 1113
情深已故
情深已故 2020-12-12 13:05

Is it possible to somehow shorten this statement?

if (obj != null)
    obj.SomeMethod();

because I happen to write this a lot and it gets p

11条回答
  •  臣服心动
    2020-12-12 13:33

    Cerating extention method like one suggested does not really solve issues with race conditions, but rather hide them.

    public static void SafeInvoke(this EventHandler handler, object sender)
    {
        if (handler != null) handler(sender, EventArgs.Empty);
    }
    

    As stated this code is the elegant equivalent to solution with temporary variable, but...

    The problem with both that it's possible that subsciber of the event could be called AFTER it has unsubscribed from the event. This is possible because unsubscription can happen after delegate instance is copied to the temp variable (or passed as parameter in the method above), but before delegate is invoked.

    In general the behaviour of the client code is unpredictable in such case: component state could not allow to handle event notification already. It's possible to write client code in the way to handle it, but it would put unnecesssary responsibility to the client.

    The only known way to ensure thread safity is to use lock statement for the sender of the event. This ensures that all subscriptions\unsubscriptions\invocation are serialized.

    To be more accurate lock should be applied to the same sync object used in add\remove event accessor methods which is be default 'this'.

提交回复
热议问题