Search code examples
c#visual-studio-2010resharper-2016

ReSharper can´t find unreachable code


I have this code:

Assert.IsTrue(datasetMetadata1 != null && datasetMetadata1.Length == 5);
Assert.IsTrue(datasetMetadata2 != null && datasetMetadata2 .Length == 11);

if ((datasetMetadata1 == null || datasetMetadata1.Length != 5) ||
(datasetMetadata2 == null || datasetMetadata2 .Length != 11)
{ 
    /* do something */ 
}

which ReSharper simplifies by removing the redundant (because allways true) expression == null and by inverting the if-statement to something similar to:

if ((datasetMetadataPunktort.Length == 5) && (datasetMetadataFlurstueck.Length == 11)) 
    return

However for me it seems even this check is meaningless and can easily be omited as the condition is allways true. So I wonder why ReSharper detects the obsolete check against null but not for the rest.

Am I missing any case where the check fails?


Solution

  • to explain my comment :

    To my mind, the thing is the following : Each time you test your value, you make a call to the getter. Resharper doesn't know if your actual getter modifies or not your value. It could be possible that the first time you call the getter it returns 5 and increments the value by 6. So next time you will have 11 returned.

    I created this small console application as a sample :

    This clas contains the parameter with the special getter.

    public class TestClass
    {
        private int _length;
    
        public int Length
        {
            get
            {
                var localLength = _length;
                _length += 6;
                return localLength;
            }
            set { _length = value; }
        }
    
        public TestClass(int length)
        {
            this._length = length;
        }
    }
    

    This class is used for test purposes :

      class Program
    {
        static void Main(string[] args)
        {
            var testObject = new TestClass(5);
            if ((testObject.Length == 5) && (testObject.Length == 11))
            {
                Console.WriteLine("TRUE");
            }
            else
            {
                Console.WriteLine("FALSE");
            }
            Console.Read();
    
        }
    }
    

    And we have the following output :

    TRUE
    

    I agree this class is very special, and has been made in the purpose to make the condition working, but still it shows that the case is possible.

    Overall, it shows that since the getter is called between each condition, the value can change, so the call is not redundant.