How to Overload Assignment Operator in C#

  • How to Overload Assignment Operator in …

Operator Overloading in C#

Use implicit conversion operators to implement assignment operator overloading in c#, c# overload assignment operator using a copy constructor, use the op_assignment method to overload the assignment operator in c#, define a property to overload assignment operator in c#.

How to Overload Assignment Operator in C#

In C#, the assignment operator ( = ) is fundamental for assigning values to variables.

However, when working with custom classes, you might want to define your behavior for the assignment operation. This process is known as overloading the assignment operator.

In this article, we will explore different methods on how to overload assignment operators using C#, providing detailed examples for each approach. Let’s first have a look at operator overloading in C#.

A method for the redefinition of a built-in operator is called operator overloading. When one or both operands are of the user-defined type, we can create user-defined implementations of many different operations.

Operator overloading in C# allows you to define custom behavior for operators when working with objects of your classes.

It provides a way to extend the functionality of operators beyond their default behavior for built-in types. This can lead to more intuitive and expressive code when dealing with custom data types.

Operators in C# are symbols that perform operations on variables and values. The basic syntax for operator overloading involves defining a special method for the operator within your class.

The method must be marked with the operator keyword followed by the operator you want to overload. Here is an example of overloading the + operator for a custom class:

In this example, the + operator is overloaded to add two instances of CustomClass together. The operator + method takes two parameters of the same type and returns a new instance with the sum of their values.

You can achieve assignment overloading by using implicit conversion operators. This method allows you to define how instances of your class can be implicitly converted to each other.

Implicit conversion operations can be developed. Making them immutable structs is another smart move.

The primitives are just that, and that is what makes it impossible to inherit from them. We’ll develop an implicit conversion operator in the example below, along with addition and other operators.

To begin, import the following libraries:

We’ll create a struct named Velocity and create a double variable called value .

Instruct Velocity to create a public Velocity receiving a variable as a parameter.

Now, we’ll create an implicit operator, Velocity .

Then, we’ll create the Addition and Subtraction operators to overload.

Lastly, in the Main() method, we’ll call the object of Velocity to overload.

Complete Source Code:

This code defines a Velocity struct with custom operators for addition and subtraction, allowing instances of the struct to be created from double values and supporting arithmetic operations. The Example class showcases the usage of this struct with implicit conversion and overloaded operators.

Another approach is to overload the assignment operator by using a copy constructor. This method involves creating a new instance of the class and copying the values from the provided object.

A copy constructor is a special type of constructor that creates a new object by copying the values of another object of the same type. It enables the creation of a deep copy, ensuring that the new object is an independent instance with the same values as the original object.

In the context of overloading the assignment operator, a copy constructor serves as an effective alternative.

In this example, the CustomClass has a private value field, a constructor to initialize it, and a copy constructor that allows us to create a new object by copying the values from an existing object.

In this scenario, obj2 is created by invoking the copy constructor with new CustomClass(obj1) . As a result, obj2 becomes a distinct object with the same values as obj1 .

This approach effectively emulates the behavior of an overloaded assignment operator.

The most common approach to overload the assignment operator is by defining a method named op_Assignment within your class. This method takes two parameters - the object being assigned to ( this ) and the value being assigned.

The op_Assignment method is a user-defined method that allows developers to customize the behavior of the assignment operator for their own types. By defining this method within a class, you can control how instances of that class are assigned values.

Consider the following CustomClass with an op_Assignment method:

In this code, the CustomClass has a private value field, a constructor to initialize it, and an op_Assignment method that allows us to customize the behavior of the assignment operator.

The obj1.op_Assignment(obj2) triggers the op_Assignment method, customizing the behavior of the assignment operator and copying the values from obj2 to obj1 .

Overloading the assignment operator using a property involves defining a property with both a getter and a setter. The setter, in this case, will be responsible for customizing the assignment behavior.

This approach provides a clean and concise syntax for assignments, making the code more readable.

Consider the following CustomClass with a property named AssignValue :

In this code, the CustomClass has a private value field, a constructor to initialize it, and a property named AssignValue that will be used to overload the assignment operator.

The obj1.AssignValue = obj2.AssignValue; triggers the setter of the AssignValue property, customizing the behavior of the assignment and copying the values from obj2 to obj1 .

In conclusion, while direct overloading of the assignment operator is not directly supported in C#, these alternative methods provide powerful and flexible ways to achieve similar functionality. Choosing the appropriate method depends on the specific requirements and design considerations of your project, and each approach offers its advantages in terms of readability, control, and encapsulation.

By mastering these techniques, developers can enhance the expressiveness and maintainability of their code when dealing with user-defined types in C#.

Muhammad Zeeshan avatar

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.

Related Article - Csharp Operator

  • Modulo Operator in C#
  • The Use of += in C#
  • C# Equals() vs ==

Tutlane Logo

C# Assignment Operators with Examples

In c#, Assignment Operators are useful to assign a new value to the operand, and these operators will work with only one operand.

For example, we can declare and assign a value to the variable using the assignment operator ( = ) like as shown below.

If you observe the above sample, we defined a variable called “ a ” and assigned a new value using an assignment operator ( = ) based on our requirements.

The following table lists the different types of operators available in c# assignment operators.

C# Assignment Operators Example

Following is the example of using assignment Operators in the c# programming language.

If you observe the above example, we defined a variable or operand “ x ” and assigning new values to that variable by using assignment operators in the c# programming language.

Output of C# Assignment Operators Example

When we execute the above c# program, we will get the result as shown below.

C# Assigenment Operator Example Result

This is how we can use assignment operators in c# to assign new values to the variable based on our requirements.

Table of Contents

  • Assignment Operators in C# with Examples
  • C# Assignment Operator Example
  • Output of C# Assignment Operator Example

Csharp Tutorial

  • C# Basic Tutorial
  • C# - Overview
  • C# - Environment
  • C# - Program Structure
  • C# - Basic Syntax
  • C# - Data Types
  • C# - Type Conversion
  • C# - Variables
  • C# - Constants
  • C# - Operators
  • C# - Decision Making
  • C# - Encapsulation
  • C# - Methods
  • C# - Nullables
  • C# - Arrays
  • C# - Strings
  • C# - Structure
  • C# - Classes
  • C# - Inheritance
  • C# - Polymorphism
  • C# - Operator Overloading
  • C# - Interfaces
  • C# - Namespaces
  • C# - Preprocessor Directives
  • C# - Regular Expressions
  • C# - Exception Handling
  • C# - File I/O
  • C# Advanced Tutorial
  • C# - Attributes
  • C# - Reflection
  • C# - Properties
  • C# - Indexers
  • C# - Delegates
  • C# - Events
  • C# - Collections
  • C# - Generics
  • C# - Anonymous Methods
  • C# - Unsafe Codes
  • C# - Multithreading
  • C# Useful Resources
  • C# - Questions and Answers
  • C# - Quick Guide
  • C# - Useful Resources
  • C# - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

C# - Assignment Operators

There are following assignment operators supported by C# −

The following example demonstrates all the assignment operators available in C# −

When the above code is compiled and executed, it produces the following result −

To Continue Learning Please Login

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

C# operator

last modified July 5, 2023

In this article we cover C# operators.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

C# operator list

The following table shows a set of operators used in the C# language.

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators . There is also one ternary operator ?: , which works with three operands.

Certain operators may be used in different contexts. For example the + operator. From the above table we can see that it is used in different cases. It adds numbers, concatenates strings or delegates; indicates the sign of a number. We say that the operator is overloaded .

C# unary operators

C# unary operators include: +, -, ++, --, cast operator (), and negation !.

C# sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to indicate that we have a positive number. It can be omitted and it is mostly done so.

The minus sign changes the sign of a value.

C# increment and decrement operators

Incrementing or decrementing a value by one is a common task in programming. C# has two convenient operators for this: ++ and -- .

The above two pairs of expressions do the same.

In the above example, we demonstrate the usage of both operators.

We initiate the x variable to 6. Then we increment x two times. Now the variable equals to 8.

We use the decrement operator. Now the variable equals to 7.

C# explicit cast operator

The explicit cast operator () can be used to cast a type to another type. Note that this operator works only on certain types.

In the example, we explicitly cast a float type to int .

Negation operator

The negation operator (!) reverses the meaning of its operand.

In the example, we build a negative condition: it is executed if the inverse of the expression is valid.

C# assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

Here we assign a number to the x variable.

The previous expression does not make sense in mathematics. But it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x .

This code example results in syntax error. We cannot assign a value to a literal.

C# concatenating strings

The + operator is also used to concatenate strings.

We join three strings together using string concatenation operator.

C# arithmetic operators

The following is a table of arithmetic operators in C#.

The following example shows arithmetic operations.

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Next we show the distinction between integer and floating point division.

In the preceding example, we divide two numbers.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

If one of the values is a double or a float, we perform a floating point division. In our case, the second operand is a double so the result is a double.

C# Boolean operators

In C#, we have three logical operators. The bool keyword is used to declare a Boolean value.

Boolean operators are also called logical.

Many expressions result in a boolean value. Boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

The true and false keywords represent boolean literals in C#.

Example shows the logical and operator. It evaluates to true only if both operands are true.

Only one expression results in True .

The logical or || operator evaluates to true, if either of the operands is true.

If one of the sides of the operator is true, the outcome of the operation is true.

Three of four expressions result in true.

The negation operator ! makes true false and false true.

The example shows the negation operator in action.

The || , and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.

An example may clarify this a bit more.

We have two methods in the example. They are used as operands in boolean expressions.

The One method returns false . The short circuit && does not evaluate the second method. It is not necessary. Once an operand is false , the result of the logical conclusion is always false . Only "Inside one" is only printed to the console.

In the second case, we use the || operator and use the Two method as the first operand. In this case, "Inside two" and "Pass" strings are printed to the terminal. It is again not necessary to evaluate the second operand, since once the first operand evaluates to true , the logical or is always true .

C# relational operators

Relational operators are used to compare values. These operators always result in boolean value.

Relational operators are also called comparison operators.

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In C# we use == to compare numbers. Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.

C# bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like C#.

The bitwise negation operator changes each 1 to 0 and 0 to 1.

The operator reverts all bits of a number 7. One of the bits also determines, whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

The first number is a binary notation of 6, the second is 3, and the result is 2.

The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.

The result is 00110 or decimal 7.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

The result is 00101 or decimal 5.

C# compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.

The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable.

Other compound operators are:

In the example, we use two compound operators.

The a variable is initiated to one. 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5; .

Using the *= operator, the a is multiplied by 3. The statement is equal to a = a * 3; .

C# new operator

The new operator is used to create objects and invoke constructors.

In the example, we create a new custom object and a array of integers utilizing the new operator.

This is a constructor. It is called at the time of the object creation.

C# access operator

The access operator [] is used with arrays, indexers, and attributes.

In the example, we use the [] operator to get an element of an array, value of a dictionary pair, and activate a built-in attribute.

We define an array of integers. We get the first element with vals[0] .

A dictionary is created. With domains["de"] , we get the value of the pair that has the "de" key.

We active the built-in Obsolete attribute. The attribute issues a warning.

When we run the program, it produces the warning: warning CS0618: 'oldMethod()' is obsolete: 'Don't use OldMethod, use NewMethod instead' .

C# index from end operator ^

The index from end operator ^ indicates the element position from the end of a sequence. For instance, ^1 points to the last element of a sequence and ^n points to the element with offset length - n .

In the example, we apply the operator on an array and a string.

We print the last and the last but one element of the array.

We print the last letter of the word.

C# range operator ..

The .. operator specifies the start and end of a range of indices as its operands. The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range.

Operands of the .. operator can be omitted to get an open-ended range.

In the example, we use the .. operator to get array slices.

We create an array slice from index 1 till index 4; the last index 4 is not included.

Here we esentially create a copy of the array.

C# type information

Now we concern ourselves with operators that work with types.

The sizeof operator is used to obtain the size in bytes for a value type. The typeof is used to obtain the System.Type object for a type.

We use the sizeof and typeof operators.

We can see that the int type is an alias for System.Int32 and the float is an alias for the System.Single type.

The is operator checks if an object is compatible with a given type.

We create two objects from user defined types.

We have a Base and a Derived class. The Derived class inherits from the Base class.

Base equals Base and so the first line prints True. The Base is also compatible with Object type. This is because each class inherits from the mother of all classes — the Object class.

The derived object is compatible with the Base class because it explicitly inherits from the Base class. On the other hand, the _base object has nothing to do with the Derived class.

The as operator is used to perform conversions between compatible reference types. When the conversion is not possible, the operator returns null. Unlike the cast operation which raises an exception.

In the above example, we use the as operator to perform casting.

We try to cast various types to the string type. But only once the casting is valid.

C# operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

To change the order of evaluation, we can use parentheses. Expressions inside parentheses are always evaluated first.

The following table shows common C# operators ordered by precedence (highest precedence first):

Operators on the same row of the table have the same precedence.

In this code example, we show a few expressions. The outcome of each expression is dependent on the precedence level.

This line prints 28. The multiplication operator has a higher precedence than addition. First, the product of 5*5 is calculated, then 3 is added.

In this case, the negation operator has a higher precedence. First, the first true value is negated to false, then the | operator combines false and true, which gives true in the end.

C# associativity rule

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity . The associativity of operators determines the order of evaluation of operators with the same precedence level.

What is the outcome of this expression, 9 or 1? The multiplication, deletion and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean, relational, and bitwise operators are all left to right associated.

On the other hand, the assignment operator is right associated.

In the example, we have two cases where the associativity rule determines the expression.

The assignment operator is right to left associated. If the associativity was left to right, the previous expression would not be possible.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.

C# null-conditional operator

A null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null. If the operand evaluates to null , the result of applying the operator is null.

In the example, we have a User class with two members: Name and Occupation . We access the name member of the objects with the help of the ?. operator.

We have a list of users. One of them is initialized with null values.

We use the ?. to access the Name member and call the ToUpper method. The ?. prevents the System.NullReferenceException by not calling the ToUpper on the null value.

In the following example, we use the ?[] operator. The operator allows to place null values into a collection.

In this example, we have a null value in an array. We prevent the System.NullReferenceException by applying the ?. operator on the array elements.

C# null-coalescing operator

The null-coalescing operator ?? is used to define a default value for a nullable type. It returns the left-hand operand if it is not null; otherwise it returns the right operand. When we work with databases, we often deal with absent values. These values come as nulls to the program. This operator is a convenient way to deal with such situations.

An example program for null-coalescing operator.

Two nullable int types are initiated to null . The int? is a shorthand for Nullable<int> . It allows to have null values assigned to int types.

We want to assign a value to z variable. But it must not be null . This is our requirement. We can easily use the null-coalescing operator for that. In case both x and y variables are null, we assign -1 to z .

C# null-coalescing assignment operator

The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . The ??= operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null. It is available in C# 8.0 and later.

In the example, we use the null-coalescing assignment operator on a list of integer values.

First, the list is assigned to null .

We use the ??= to assign a new list object to the variable. Since it is null , the list is assigned.

We add some values to the list and print its contents.

We try to assign a new list object to the variable. Since the variable is not null anymore, the list is not assigned.

C# ternary operator

The ternary operator ?: is a conditional operator. It is a convenient operator for cases where we want to pick up one of two values, depending on the conditional expression.

If cond-exp is true, exp1 is evaluated and the result is returned. If the cond-exp is false, exp2 is evaluated and its result is returned.

In most countries the adulthood is based on your age. You are adult if you are older than a certain age. This is a situation for a ternary operator.

First the expression on the right side of the assignment operator is evaluated. The first phase of the ternary operator is the condition expression evaluation. So if the age is greater or equal to 18, the value following the ? character is returned. If not, the value following the : character is returned. The returned value is then assigned to the adult variable.

A 31 years old person is adult.

C# Lambda operator

The => token is called the lambda operator. It is an operator taken from functional languages. This operator can make the code shorter and cleaner. On the other hand, understanding the syntax may be tricky. Especially if a programmer never used a functional language before.

Wherever we can use a delegate, we also can use a lambda expression. A definition for a lambda expression is: a lambda expression is an anonymous function that can contain expressions and statements. On the left side we have a group of data and on the right side an expression or a block of statements. These statements are applied on each item of the data.

In lambda expressions we do not have a return keyword. The last statement is automatically returned. And we do not need to specify types for our parameters. The compiler will guess the correct parameter type. This is called type inference.

We have a list of integer numbers. We print all numbers that are greater than 3.

We have a generic list of integers.

Here we use the lambda operator. The FindAll method takes a predicate as a parameter. A predicate is a special kind of a delegate that returns a boolean value. The predicate is applied for all items of the list. The val is an input parameter specified without a type. We could explicitly specify the type but it is not necessary.

The compiler will expect an int type. The val is a current input value from the list. It is compared if it is greater than 3 and a boolean true or false is returned. Finally, the FindAll will return all values that met the condition. They are assigned to the sublist collection.

The items of the sublist collection are printed to the terminal.

Values from the list of integers that are greater than 3.

This is the same example. We use a anonymous delegate instead of a lambda expression.

C# calculating prime numbers

We are going to calculate prime numbers.

In the above example, we deal with many various operators. A prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. We pick up a number and divide it by numbers, from 1 up to the picked up number. Actually, we do not have to try all smaller numbers; we can divide by numbers up to the square root of the chosen number. The formula will work. We use the remainder division operator.

We calculate primes from these numbers.

By definition, 1 is not a prime

We skip the calculations for 2 and 3: they are primes. Note the usage of the equality and conditional or operators. The == has a higher precedence than the || operator. So we do not need to use parentheses.

We are OK if we only try numbers smaller than the square root of a number in question. It was mathematically proven that it is sufficient to take into account values up to the square root of the number in question.

This is a while loop. The i is the calculated square root of the number. We use the decrement operator to decrease the i by one each loop cycle. When the i is smaller than 1, we terminate the loop. For example, we have number 9. The square root of 9 is 3. We divide the 9 number by 3 and 2.

This is the core of the algorithm. If the remainder division operator returns 0 for any of the i values then the number in question is not a prime.

C# operators and expressions

In this article we covered C# operators.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials .

C# in a Nutshell by

Get full access to C# in a Nutshell and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Operator Overloading

C# lets you overload operators to work with operands that are custom classes or structs using operators. An operator is a static method with the keyword operator preceding the operator to overload (instead of a method name), parameters representing the operands, and return types representing the result of an expression. Table 4-1 lists the available overloadable operators.

Table 4-1. Overloadable operators

Literals that also act as overloadable operators are true and false .

Implementing Value Equality

A pair of references exhibit referential equality when both references point to the same object. By default, the == and != operators will compare two reference-type variables by reference. However, it is occasionally more natural for the == and != operators to exhibit value equality, whereby the comparison is based on the value of the objects that the references point to.

Whenever overloading the == and != operators, you should always override the virtual Equals method to route its functionality to the == operator. This allows a class to be used polymorphically (which is essential if you want to take advantage of functionality such as the collection classes). It also provides compatibility with other .NET languages that don’t overload operators.

A good guideline for knowing whether to implement the == and != operators is if it is natural for the class to overload other operators too, such as < , > , + , or - ; otherwise, don’t bother — just implement the Equals method. For structs, overloading the == and != operators provides a more efficient implementation than the default one.

Logically Paired Operators

The C# compiler enforces operators that are logical pairs to both be defined. These operators are == != , < > , and <= >= .

Custom Implicit and Explicit Conversions

As explained in the discussion on types, the rationale behind implicit conversions is they are guaranteed to succeed and do not lose information during the conversion. Conversely, an explicit conversion is required either when runtime circumstances will determine whether the conversion will succeed or if information may be lost during the conversion. In this example, we define conversions between our musical Note type and a double (which represents the frequency in hertz of that note):

Three-State Logic Operators

The true and false keywords are used as operators when defining types with three-state logic to enable these types to work seamlessly with constructs that take boolean expressions — namely, the if , do , while , for , and conditional (?:) statements. The System.Data.SQLTypes.SQLBoolean struct provides this functionality:

Indirectly Overloadable Operators

The && and || operators are automatically evaluated from & and | , so they do not need to be overloaded. The [] operators can be customized with indexers (see Section 3.1.5 in Chapter 3 ). The assignment operator = cannot be overloaded, but all other assignment operators are automatically evaluated from their corresponding binary operators (e.g., += is evaluated from + ).

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

custom assignment operator c#

C# Tutorial

C# examples, c# assignment operators, assignment operators.

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

Try it Yourself »

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

addition-operator.md

Latest commit, file metadata and controls, + and += operators (c# reference).

The + operator is supported by the built-in numeric types, 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:

[!code-csharp-interactive string concatenation ]

Starting with C# 6, string interpolation provides a more convenient way to format strings:

[!code-csharp-interactive string interpolation ]

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-interactive delegate 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

is equivalent to

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 cannot explicitly overload the += operator.

C# language specification

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

  • C# reference
  • C# operators
  • String interpolation
  • How to: concatenate multiple strings
  • Arithmetic operators
  • - and -= operators

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

C# operators and expressions

  • 13 contributors

C# provides a number of operators. Many of them are supported by the built-in types and allow you to perform basic operations with values of those types. Those operators include the following groups:

  • Arithmetic operators that perform arithmetic operations with numeric operands
  • Comparison operators that compare numeric operands
  • Boolean logical operators that perform logical operations with bool operands
  • Bitwise and shift operators that perform bitwise or shift operations with operands of the integral types
  • Equality operators that check if their operands are equal or not

Typically, you can overload those operators, that is, specify the operator behavior for the operands of a user-defined type.

The simplest C# expressions are literals (for example, integer and real numbers) and names of variables. You can combine them into complex expressions by using operators. Operator precedence and associativity determine the order in which the operations in an expression are performed. You can use parentheses to change the order of evaluation imposed by operator precedence and associativity.

In the following code, examples of expressions are at the right-hand side of assignments:

Typically, an expression produces a result and can be included in another expression. A void method call is an example of an expression that doesn't produce a result. It can be used only as a statement , as the following example shows:

Here are some other kinds of expressions that C# provides:

Interpolated string expressions that provide convenient syntax to create formatted strings:

Lambda expressions that allow you to create anonymous functions:

Query expressions that allow you to use query capabilities directly in C#:

You can use an expression body definition to provide a concise definition for a method, constructor, property, indexer, or finalizer.

Operator precedence

In an expression with multiple operators, the operators with higher precedence are evaluated before the operators with lower precedence. In the following example, the multiplication is performed first because it has higher precedence than addition:

Use parentheses to change the order of evaluation imposed by operator precedence:

The following table lists the C# operators starting with the highest precedence to the lowest. The operators within each row have the same precedence.

For information about the precedence of logical pattern combinators , see the Precedence and order of checking of logical patterns section of the Patterns article.

Operator associativity

When operators have the same precedence, associativity of the operators determines the order in which the operations are performed:

  • Left-associative operators are evaluated in order from left to right. Except for the assignment operators and the null-coalescing operators , all binary operators are left-associative. For example, a + b - c is evaluated as (a + b) - c .
  • Right-associative operators are evaluated in order from right to left. The assignment operators, the null-coalescing operators, lambdas, and the conditional operator ?: are right-associative. For example, x = y = z is evaluated as x = (y = z) .

In an expression of the form P?.A0?.A1 , if P is null , neither A0 nor A1 are evaluated. Similarly, in an expression of the form P?.A0.A1 , because A0 isn't evaluated when P is null, neither is A0.A1 . See the C# language specification for more details.

Use parentheses to change the order of evaluation imposed by operator associativity:

Operand evaluation

Unrelated to operator precedence and associativity, operands in an expression are evaluated from left to right. The following examples demonstrate the order in which operators and operands are evaluated:

Typically, all operator operands are evaluated. However, some operators evaluate operands conditionally. That is, the value of the leftmost operand of such an operator defines if (or which) other operands should be evaluated. These operators are the conditional logical AND ( && ) and OR ( || ) operators, the null-coalescing operators ?? and ??= , the null-conditional operators ?. and ?[] , and the conditional operator ?: . For more information, see the description of each operator.

C# language specification

For more information, see the following sections of the C# language specification :

  • Expressions
  • Operator overloading
  • Expression trees

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

  • .NET Framework
  • C# Data Types
  • C# Keywords
  • C# Decision Making
  • C# Delegates
  • C# Constructors
  • C# ArrayList
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception

Null-Coalescing Assignment Operator in C# 8.0

  • Null-Coalescing Operator in C#
  • Object and Collection Initializer in C#
  • Nullish Coalescing Assignment (??=) Operator in JavaScript
  • Assignment Operators in C
  • Assignment Operators In C++
  • Move Assignment Operator in C++ 11
  • How to Implement Move Assignment Operator in C++?
  • Compound assignment operators in Java
  • How to Create Custom Assignment Operator in C++?
  • JavaScript Assignment Operators
  • JavaScript Nullish Coalescing(??) Operator
  • Default Assignment Operator and References in C++
  • Self assignment check in assignment operator
  • Java Assignment Operators with Examples
  • Ternary operator vs Null coalescing operator in PHP
  • Assignment Operators in Programming
  • C++ Assignment Operator Overloading
  • What is the use of Null Coalesce Operator ?
  • SQL IS NOT NULL Operator

C# 8.0 has introduced a new operator that is known as a Null-coalescing assignment operator( ??= ). This operator is used to assign the value of its right-hand operand to its left-hand operand, only if the value of the left-hand operand is null. If the left-hand operand evaluates to non-null, then this operator does not evaluate its right-hand operand.

Here, p is the left and q is the right operand of ??= operator. If the value of p is null, then ??= operator assigns the value of q in p. Or if the value of p is non-null, then it does not evaluate q.

Important Points:

  • The left-hand operand of the ??= operator must be a variable, or a property, or an indexer element.
  • It is right-associative.
  • You cannot overload ??= operator.

Please Login to comment...

Similar reads.

author

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. C# Assignment Operators with Examples

    custom assignment operator c#

  2. [100% Working Code]

    custom assignment operator c#

  3. assignment operator in C# Programming

    custom assignment operator c#

  4. C# Assignment Operators

    custom assignment operator c#

  5. Assignment Operators in C#.Net

    custom assignment operator c#

  6. Assignment Operators in C++

    custom assignment operator c#

VIDEO

  1. Assignment 06

  2. Arithmetic Operator

  3. Painting Estimator c# Project

  4. C++

  5. C++

  6. C++

COMMENTS

  1. Overloading assignment operator in C#

    There is already a special instance of overloading = in place that the designers deemed ok: property setters. Let X be a property of foo. In foo.X = 3, the = symbol is replaced by the compiler by a call to foo.set_X(3). You can already define a public static T op_Assign(ref T assigned, T assignee) method. All that is left is for the compiler to ...

  2. Assignment operators

    In this article. The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or ...

  3. Operator overloading

    A user-defined type can overload a predefined C# operator. That is, a type can provide the custom implementation of an operation in case one or both of the operands are of that type. The Overloadable operators section shows which C# operators can be overloaded. Use the operator keyword to declare an operator. An operator declaration must ...

  4. User-defined explicit and implicit conversion operators

    For more information, see the User-defined checked operators section of the Arithmetic operators article. You also use the operator keyword to overload a predefined C# operator. For more information, see Operator overloading. C# language specification. For more information, see the following sections of the C# language specification: Conversion ...

  5. How to Overload Assignment Operator in C#

    The obj1.op_Assignment(obj2) triggers the op_Assignment method, customizing the behavior of the assignment operator and copying the values from obj2 to obj1. Define a Property to Overload Assignment Operator in C#. Overloading the assignment operator using a property involves defining a property with both a getter and a setter.

  6. docs/docs/csharp/language-reference/operators/assignment ...

    Assignment operators (C# reference) The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the ...

  7. C# Assignment Operators with Examples

    In c#, Assignment Operators are useful to assign a new value to the operand, and these operators will work with only one operand. For example, we can declare and assign a value to the variable using the assignment operator ( =) like as shown below. int a; a = 10; If you observe the above sample, we defined a variable called " a " and ...

  8. C#

    Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B assigns value of A + B into C. +=. Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A.

  9. C#

    Operators are used to perform various operations on variables and values.. Syntax. The following code snippet uses the assignment operator, =, to set myVariable to the value of num1 and num2 with an arithmetic operator operating on them. For example, if operator represented *, myVariable would be assigned a value of num1 * num2.. myVariable = num1 operator num2;

  10. Is it possible to create a new operator in c#?

    20. As the other answers have said, you can't create a new operator - at least, not without altering the lexer and parser that are built into the compiler. Basically, the compiler is built to recognize that an individual character like < or ?, or a pair like >> or <=, is an operator and to treat it specially; it knows that i<5 is an expression ...

  11. Make assignment operator overloadable for "transitional ...

    Looks and behaves, because it is redefining the assignment operator. If you want to argue that the language should lift the restriction on overloading the assignment operator, fine. But don't frame your proposal that it's somehow not overloading the assignment operator and thus any argument against overloading the assignment operator doesn't apply.

  12. C# operator

    C# compound assignment operators. The compound assignment operators consist of two operators. They are shorthand operators. a = a + 3; a += 3; The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable. Other compound operators are:

  13. Operator Overloading

    C# lets you overload operators to work with operands that are custom classes or structs using operators. An operator is a static method with the keyword operator preceding the operator to overload (instead of a method name), parameters representing the operands, and return types representing the result of an expression.Table 4-1 lists the available overloadable operators.

  14. C# Assignment Operators

    C# Assignment Operators Previous Next Assignment Operators. Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: Example int x = 10;

  15. c#

    public Field<T> WithValue(T value) {. return new Field<T>(this.Ordinal, this.Number, value); } And then call it like this: dateOfBirth = dateOfBirth.WithValue(DateTime.Today); Also note, I'd strongly recommend making the operator T explicit, because it discards the Ordinal and Numeric values. See this note from MSDN:

  16. dotnetdocs/docs/csharp/language-reference/operators/addition-operator

    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:

  17. Shorthand Operators in C#: Streamlining Your Code

    Assignment Operators: Assignment operators modify the value of a variable. Their symbols are: ... Shorthand operators are an invaluable tool for C# developers, enabling them to write more concise ...

  18. Operators and expressions

    In this article. C# provides a number of operators. Many of them are supported by the built-in types and allow you to perform basic operations with values of those types. Those operators include the following groups: Arithmetic operators that perform arithmetic operations with numeric operands; Comparison operators that compare numeric operands; Boolean logical operators that perform logical ...

  19. Is it possible to override assignment "=" in C#

    3. No, this is not possible. The assignment operator is not overridable and for good reason. Developers are, even within the confines of C# and modern object-oriented programming languages, often "abusing" the system to make it do things it's not supposed to do.

  20. Null-Coalescing Assignment Operator in C# 8.0

    A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

  21. Is it possible to make custom operators in C#?

    5. No, C# does not allow custom operators. You can overload certain pre-existing ones, but you cannot create your own like in Haskell or F#. answered May 24, 2011 at 16:10. Gabe.