0

Given the following basic class:


public class MyClass
{
    private object m_memberVariable;

    public MyClass()
    {
       this.m_memberVariable = new object();
    }
}

Which of the following implementations of the test method is better programming practice?


private void test()
{
   if(this.m_memberVariable == null)
   {
       return;
   }
   System.Diagnostics.Debug.Write(this.m_memberVariable.ToString());
}
Or

private void test()
{
   if(this.m_memberVariable != null)
   {
       System.Diagnostics.Debug.Write(this.m_memberVariable.ToString());
   }
}

In trying to recollect from a professor some 10 years ago, best practice for an if statement is to have the condition that is likely to be true more often than false (the latter). However, recently I have been using a trial of ReSharper, and their suggestion is the former. The m_memberVariable member is initialized at instantiation of the class and will likely be non-null for the life of the class.

4

1 回答 1

0

我总是尝试检查非 null 并继续 - 然后您只有一个函数退出点,因此退出例程必须仅放置在二进制代码中一次,这会导致较小的结果。但我猜现代编译器无论如何都会优化它,谁知道呢。

于 2012-10-26T18:23:28.770 回答