Skip to content

Latest commit

 

History

History
83 lines (54 loc) · 4.21 KB

addition-operator.md

File metadata and controls

83 lines (54 loc) · 4.21 KB
title description ms.date f1_keywords helpviewer_keywords
Addition operators - + and +=
The C# addition operators (`+`, and `+=`) work with operands of numeric, string, or delegate types.
11/29/2022
+_CSharpKeyword
+=_CSharpKeyword
addition operator [C#]
concatenation operator [C#]
delegate combination [C#]
+ operator [C#]
addition assignment operator [C#]
event subscription [C#]
+= operator [C#]

Addition operators - + and +=

The + and += operators are supported by the built-in integral and floating-point numeric types, the string type, and delegate types.

For information about the arithmetic + operator, see the Unary plus and minus operators and Addition operator + sections of the Arithmetic operators article.

String concatenation

When one or both operands are of type string, the + operator concatenates the string representations of its operands (the string representation of null is an empty string):

[!code-csharp-interactivestring concatenation]

String interpolation provides a more convenient way to format strings:

[!code-csharp-interactivestring interpolation]

Beginning with C# 10, you can use string interpolation to initialize a constant string when all the expressions used for placeholders are also constant strings.

Beginning with C# 11, the + operator performs string concatenation for UTF-8 literal strings. This operator concatenates two ReadOnlySpan<byte> objects.

Delegate combination

For operands of the same delegate type, the + operator returns a new delegate instance that, when invoked, invokes the left-hand operand and then invokes the right-hand operand. If any of the operands is null, the + operator returns the value of another operand (which also might be null). The following example shows how delegates can be combined with the + operator:

[!code-csharp-interactivedelegate combination]

To perform delegate removal, use the - operator.

For more information about delegate types, see Delegates.

Addition assignment operator +=

An expression using the += operator, such as

x += y

is equivalent to

x = x + y

except that x is only evaluated once.

The following example demonstrates the usage of the += operator:

[!code-csharp-interactive+= examples]

You also use the += operator to specify an event handler method when you subscribe to an event. For more information, see How to: subscribe to and unsubscribe from events.

Operator overloadability

A user-defined type can overload the + operator. When a binary + operator is overloaded, the += operator is also implicitly overloaded. A user-defined type can't explicitly overload the += operator.

C# language specification

For more information, see the Unary plus operator and Addition operator sections of the C# language specification.

See also