본문 바로가기
IT Study/C#

[C#] Null이 아니라 EventArgs.Empty를 사용하는 이유?

by dev_huhu 2021. 5. 27.
반응형

코드를 쓰면서 밑의 두 가지 모두의 코드를 많이 접했는데

sender object와 event argument가 필요 없는 상황에서 이벤트 처리 메서드를 일반적으로 사용할 때 어떤 Param을 넘겨야 하고 어떤 차이가 있는걸까?

 

protected virtual OnSomethingHappened()
{
    this.SomethingHappened(this, EventArgs.Empty);
}

 

protected virtual OnSomethingHappened()
{
    this.SomethingHappened(null, null);
}

 

그에 대한 답은 스택 오버플로우에 정리 되어있었다.

Null을 전달하고 e로 무언가를 시도했을 때 발생하는 잠재적인 Null 참조 예외를 피하기 위함.

 

https://stackoverflow.com/questions/188692/why-use-eventargs-empty-instead-of-null

 

Why use EventArgs.Empty instead of null?

I recall reading, on multiple occasions and in multiple locations, that when firing the typical event: protected virtual OnSomethingHappened() { this.SomethingHappened(this, EventArgs.Empty); ...

stackoverflow.com

 

해당 글의 답변 중 EventArgs.Empty 대신 new EventArgs()를 사용해왔다는 분도 계신데...

난 네이밍도 직관적이고 저렇게 만들어진 데에는 이유가 있을거라는 생각으로 전자를 선호한다.

 

반응형

댓글