Method call if not null in C#

后端 未结 11 1104
情深已故
情深已故 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:18

    Events can be initialized with an empty default delegate which is never removed:

    public event EventHandler MyEvent = delegate { };
    

    No null-checking necessary.

    [Update, thanks to Bevan for pointing this out]

    Be aware of the possible performance impact, though. A quick micro benchmark I did indicates that handling an event with no subscribers is 2-3 times slower when using the the "default delegate" pattern. (On my dual core 2.5GHz laptop that means 279ms : 785ms for raising 50 million not-subscribed events.). For application hot spots, that might be an issue to consider.

提交回复
热议问题