0

I just started using Resharper and I'm getting the "Redundant check before assignment" warning and I'd like to know if the runtime really does check for equality and skip reassigning the value. I've seen the other posts about immutable or primitive or complex values and the cost involved in checking for equality vs. the cost of re-assigning equal values, and that's not my concern.

My concern is that the when setter on one property calls the setter on a second property and that second setter is costly because of a network call, for example. If the runtime does not actually check for equality before assignment, I'd need to do it myself to prevent the unnecessary second setter from running. If it does check for equality and not re-assign, I'd rather not do the redundant check to improve performance and readability.

So, does .NET 4.7 check property values before assignment?

Kevin S. Miller
  • 913
  • 1
  • 9
  • 21
  • 3
    Can you include a code example? Makes it easier to reason about it. – Jeroen Vannevel Dec 29 '17 at 16:19
  • 1
    Well, you could do a test. Put a break point in the second property setter and see if it's called when you try to assign the same value. – Magnetron Dec 29 '17 at 16:25
  • 2
    I seriously doubt that .NET would ignore setting a property, especially given that custom logic could be running on the back end. Resharper can be a useful tool but in my experience has a high rate of false positives. – BJ Myers Dec 29 '17 at 16:27
  • 4
    `...and that second setter is costly because of a network call...` - Then it is not a good candidate for a property. Per [Choosing Between Properties and Methods on MSDN](https://msdn.microsoft.com/en-us/library/ms229054(v=vs.100).aspx), you should `use a method, rather than a property when the operation is orders of magnitude slower than a field set would be`. – NightOwl888 Dec 29 '17 at 18:36
  • A question like "why does ReSharper say `something` on inspecting `some code`" **really needs to include the `some code` in question** – AakashM Jan 02 '18 at 11:50

1 Answers1

1

Just checked with the code below, it doesn't check for equality before assign:

Test t = new Test();
t.MyValue = 1;
t.MyValue = 1;

public class Test
{
    public Test()
    {
        
    }

    private int myValue;
    public int MyValue
    {
        get
        {
            return myValue;
        }

        set
        {
            myValue = value;
            Console.WriteLine($"Setter Called value->{myValue}");
        }
    }
}

Output:

Setter Called value->1

Setter Called value->1

Community
  • 1
  • 1
Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • For anyone coming upon this thread later, the answer is "No". This test proves it. I also did a similar test on my own system with .NET 4.7 and got the same results. – Kevin S. Miller Dec 29 '17 at 20:18