Kaleb Pederson Kaleb Pederson - 18 days ago 8
C# Question

Redundant condition check before assignment suggestion for C# in Resharper 5

Is the condition check really redundant in the following sample?:

public class MyClass {
public bool MyProperty { get; set; }

public void DoSomething(bool newValue) {
// R# says: redundant condition check before assignment
// on the following line:
if (MyProperty != newValue) { // <======
MyProperty = newValue;
}
}
}


I know that either way
MyProperty
will be set to
newValue
, but is the check redundant?

In Adobe Flex, the getter is called implicitly by the VM its running on whenever a setter is called even though no explicit check is being made. The end result is that checking before an assignment results in two checks, one explicit and one implicit, resulting in a redundant check. Does anything similar happen in C#?

Answer

There are only two situations where I've seen this type of check.

The first is when there is an additional line of code which sets another property on the object to True to indicate that the object has been modified. This is typically used when trying to decide whether to persist the state of the object to something like a database.

The second situation is when the types in question are immutable. You might want to avoid setting the value and therefore creating a new string, for example, when the values are the same. Even then, I've only seen it in certain apps where memory usage is critical.

Comments