[C#] 프로퍼티가 아닌 메서드로 구현해야 할 때

  • Post author:
  • Post category:
  • Post comments:2 Comments
  • Post last modified:December 24, 2008
private int _memberValue = 0;

public string NextValue
{
	get
	{
		_memberValue++;
		return "값";
	}
}

문제. 이 코드에 어떤 잠재적 위험이 있는지 기술하시오.

정답. 디버깅시 디버거가 NextValue 프로퍼티를 자동으로 호출하여 멤버 변수 _memberValue의 값이 예기치 않게 변할 수 있다. 이같은 문제를 피하려면 프로퍼티가 아닌 메서드를 쓰면 된다. 이와 유사한 문제를 다룬 글로는 ToString은 잘 짜야 한다란 게 있다.

This Post Has 2 Comments

  1. 홍민희

    애초에 프로퍼티의 getter는 deterministic해야하지 않을까 생각합니다.

  2. 최재훈

    역시 그래야겠죠. 디버거 생각을 못해서…

Leave a Reply to 홍민희 Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.