Code inspection: Use compound assignment
This inspection suggests using a compound assignment expression to make the code more concise and easier to read. Compound assignments are shorthand ways of combining arithmetic, boolean, bitwise, and other binary operators with the assignment operator =
. They can help reduce repetitive code and make the intent of the code clearer.
The most commonly used compound assignment expression is probably the addition assignment (x += y
), but there are other compound assignments that can come in handy. Here are some examples:
// To null-coalescing assignment
obj = obj ?? new object();
// To bitwise left shift assignment
myItem = myItem << 1;
// To modulus assignment
myValue = myValue % 3;
// To null-coalescing assignment
obj ??= new object();
// To bitwise left shift assignment
myItem = <<= 1;
// To modulus assignment
myValue %= 3;
Last modified: 08 April 2024