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# −

Operator Description Example
= 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
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

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

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

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:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

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.

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.

OperatorNameDescriptionExample
= Equal to It is used to assign the values to variables. int a; a = 10
+= Addition Assignment It performs the addition of left and right operands and assigns a result to the left operand. a += 10 is equals to a = a + 10
-= Subtraction Assignment It performs the subtraction of left and right operands and assigns a result to the left operand. a -= 10 is equals to a = a - 10
*= Multiplication Assignment It performs the multiplication of left and right operands and assigns a result to the left operand. a *= 10 is equals to a = a * 10
/= Division Assignment It performs the division of left and right operands and assigns a result to the left operand. a /= 10 is equals to a = a / 10
%= Modulo Assignment It performs the modulo operation on two operands and assigns a result to the left operand. a %= 10 is equals to a = a % 10
&= Bitwise AND Assignment It performs the Bitwise AND operation on two operands and assigns a result to the left operand. a &= 10 is equals to a = a & 10
|= Bitwise OR Assignment It performs the Bitwise OR operation on two operands and assigns a result to the left operand. a |= 10 is equals to a = a | 10
^= Bitwise Exclusive OR Assignment It performs the Bitwise XOR operation on two operands and assigns a result to the left operand. a ^= 10 is equals to a = a ^ 10
>>= Right Shift Assignment It moves the left operand bit values to the right based on the number of positions specified by the second operand. a >>= 2 is equals to a = a >> 2
<<= Left Shift Assignment It moves the left operand bit values to the left based on the number of positions specified by the second operand. a <<= 2 is equals to a = a << 2

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

Operators in C#

Back to: C#.NET Tutorials For Beginners and Professionals

Operators in C# with Examples

In this article, I am going to discuss Operators in C# with Examples. Please read our previous article, where we discussed Variables in C# with Examples. The Operators are the foundation of any programming language. Thus, the functionality of the C# language is incomplete without the use of operators. At the end of this article, you will understand what are Operators and when, and how to use them in C# Application with examples.

What are Operators in C#?

Operators in C# are symbols that are used to perform operations on operands. For example, consider the expression  2 + 3 = 5 , here 2 and 3 are operands , and + and = are called operators . So, the Operators in C# are used to manipulate the variables and values in a program.

int x = 10, y = 20; int result1 = x + y; //Operator Manipulating Variables, where x and y are variables and + is operator int result2 = 10 + 20; //Operator Manipulating Values, where 10 and 20 are value and + is operator

Types of Operators in C#:

The Operators are classified based on the type of operations they perform on operands in C# language. They are as follows:

Arithmetic Operators in C#

Addition Operator (+): The + operator adds two operands. As this operator works with two operands, so, this + (plus) operator belongs to the category of the binary operator. The + Operator adds the left-hand side operand value with the right-hand side operand value and returns the result. For example: int a=10; int b=5; int c = a+b; //15, Here, it will add the a and b operand values i.e. 10 + 5

Subtraction Operator (-): The – operator subtracts two operands. As this operator works with two operands, so, this – (minus) operator belongs to the category of the binary operator. The Minus Operator substracts the left-hand side operand value from the right-hand side operand value and returns the result. For example: int a=10; int b=5; int c = a-b; //5, Here, it will subtract b from a i.e. 10 – 5

Multiplication Operator (*): The * (Multiply) operator multiplies two operands. As this operator works with two operands, so, this * (Multiply) operator belongs to the category of the binary operator. The Multiply Operator multiplies the left-hand side operand value with the right-hand side operand value and returns the result. For example: int a=10; int b=5; int c=a*b; //50, Here, it will multiply a with b i.e. 10 * 5

Modulus Operator (%): The % (Modulos) operator returns the remainder when the first operand is divided by the second. As this operator works with two operands, so, this % (Modulos) operator belongs to the category of the binary operator. For example: int a=10; int b=5; int c=a%b; //0, Here, it will divide 10 / 5 and it will return the remainder which is 0 in this case

Example to Understand Arithmetic Operators in C#:

In the following example, I am showing how to use Arithmetic Operators with Operand which are values. Here, 10 and 20 are values and all the Arithmetic Operators are working on these two values.

Assignment Operators in C#:

The Assignment Operators in C# are used to assign a value to a variable. The left-hand side operand of the assignment operator is a variable and the right-hand side operand of the assignment operator can be a value or an expression that must return some value and that value is going to assign to the left-hand side variable.

The most important point that you need to keep in mind is that the value on the right-hand side must be of the same data type as the variable on the left-hand side else you will get a compile-time error. The different Types of Assignment Operators supported in the C# language are as follows:

Simple Assignment (=):

Add assignment (+=):.

This operator is the combination of + and = operators. It is used to add the left-hand side operand value with the right-hand side operand value and then assign the result to the left-hand side variable. For example: int a=5; int b=6; a += b; //a=a+b; That means (a += b) can be written as (a = a + b)

Subtract Assignment (-=):

This operator is the combination of – and = operators. It is used to subtract the right-hand side operand value from the left-hand side operand value and then assign the result to the left-hand side variable.  For example: int a=10; int b=5; a -= b; //a=a-b; That means (a -= b) can be written as (a = a – b)

Multiply Assignment (*=):

Division assignment (/=):.

This operator is the combination of / and = operators. It is used to divide the left-hand side operand value with the right-hand side operand value and then assign the result to the left-hand side variable.  For example: int a=10; int b=5; a /= b; //a=a/b; That means (a /= b) can be written as (a = a / b)

Modulus Assignment (%=):

This operator is the combination of % and = operators. It is used to divide the left-hand side operand value with the right-hand side operand value and then assigns the remainder of this division to the left-hand side variable.  For example: int a=10; int b=5; a %= b; //a=a%b; That means (a %= b) can be written as (a = a % b)

Example to Understand Assignment Operators in C#:

Relational operators in c#:.

The Relational Operators in C# are also known as Comparison Operators. It determines the relationship between two operands and returns the Boolean results, i.e. true or false after the comparison. The Different Types of Relational Operators supported by C# are as follows.

Equal to (==):

This Operator is used to return true if the left-hand side operand value is equal to the right-hand side operand value. For example, 5==3 is evaluated to be false. So, this Equal to (==) operator will check whether the two given operand values are equal or not. If equal returns true else returns false.

Not Equal to (!=):

Less than (<):.

This Operator is used to return true if the left-hand side operand value is less than the right-hand side operand value. For example, 5<3 is evaluated to be false. So, this Less than (<) operator will check whether the first operand value is less than the second operand value or not. If so, returns true else returns false.

Less than or equal to (<=):

This Operator is used to return true if the left-hand side operand value is less than or equal to the right-hand side operand value. For example, 5<=5 is evaluated to be true. So. this Less than or equal to (<=) operator will check whether the first operand value is less than or equal to the second operand value. If so returns true else returns false.

Greater than (>):

Greater than or equal to (>=):.

This Operator is used to return true if the left-hand side operand value is greater than or equal to the right-hand side operand value. For example, 5>=5 is evaluated to be true. So, this Greater than or Equal to (>=) operator will check whether the first operand value is greater than or equal to the second operand value. If so, returns true else returns false.

Example to Understand Relational Operators in C#:

Logical operators in c#:, logical or (||):.

This operator is used to return true if either of the Boolean expressions is true. For example, false || true is evaluated to be true. That means the Logical OR (||) operator returns true when one (or both) of the conditions in the expression is satisfied. Otherwise, it will return false. For example, a || b returns true if either a or b is true. Also, it returns true when both a and b are true.

Logical AND (&&):

This operator is used to return true if all the Boolean Expressions are true. For example, false && true is evaluated to be false. That means the Logical AND (&&) operator returns true when both the conditions in the expression are satisfied. Otherwise, it will return false. For example, a && b return true only when both a and b are true.

Logical NOT (!):

Example to understand logical operators in c#:, bitwise operators in c#:, bitwise or (|).

Bitwise OR operator is represented by |. This operator performs the bitwise OR operation on the corresponding bits of the two operands involved in the operation. If either of the bits is 1, it gives 1. If not, it gives 0. For example, int a=12, b=25; int result = a|b; //29 How? 12 Binary Number: 00001100 25 Binary Number: 00011001 Bitwise OR operation between 12 and 25: 00001100 00011001 ======== 00011101 (it is 29 in decimal) Note : If the operands are of type bool, the bitwise OR operation is equivalent to the logical OR operation between them.

Bitwise AND (&):

Bitwise OR operator is represented by &. This operator performs the bitwise AND operation on the corresponding bits of two operands involved in the operation. If both of the bits are 1, it gives 1. If either of the bits is not 1, it gives 0. For example, int a=12, b=25; int result = a&b; //8 How? 12 Binary Number: 00001100 25 Binary Number: 00011001 Bitwise AND operation between 12 and 25: 00001100 00011001 ======== 00001000 (it is 8 in decimal) Note : If the operands are of type bool, the bitwise AND operation is equivalent to the logical AND operation between them.

Bitwise XOR (^):

Example to understand bitwise operators in c#:.

In the above example, we are using BIT Wise Operators with integer data type and hence it performs the Bitwise Operations. But, if use BIT-wise Operators with boolean data types, then these bitwise operators AND, OR, and XOR behaves like Logical AND, and OR operations. For a better understanding, please have a look at the below example. In the below example, we are using the BIT-wise operators on boolean operands and hence they are going to perform the Logical AND, OR, and XOR Operations.

Note: The point that you need to remember while working with BIT-Wise Operator is that, depending on the operand on which they are working, the behavior is going to change. It means if they are working with integer operands, they will work like bitwise operators and return the result as an integer and if they are working with boolean operands, then work like logical operators and return the result as a boolean.

Unary Operators in C#:

The Unary Operators in C# need only one operand. They are used to increment or decrement a value. There are two types of Unary Operators. They are as follows:

Increment Operator (++) in C# Language:

Post increment operators:.

Syntax:  Variable++; Example:  x++;

Pre-Increment Operators:

Decrement operators in c# language:.

The Decrement Operator (–) is a unary operator. It takes one value at a time. It is again classified into two types. They are as follows:

Post Decrement Operators:

Pre-decrement operators:.

The Pre-Decrement Operators are the operators that are a prefix to its variable. It is placed before the variable. For example, –a will decrease the value of the variable a by 1.

Note:  Increment Operator means to increment the value of the variable by 1 and Decrement Operator means to decrement the value of the variable by 1.

Example to Understand Increment Operators in C# Language:

Example to understand decrement operators in c# language:, five steps to understand how the unary operators works in c#.

I see, many of the students and developers getting confused when they use increment and decrement operators in an expression. To make you understand how exactly the unary ++ and — operators work in C#, we need to follow 5 simple steps. The steps are shown in the below diagram.

Example to Understand Increment and Decrement Operators in C# Language:

Let us see one complex example to understand this concept. Please have a look at the following example. Here, we are declaring three variables x, y, and z, and then evaluating the expression as z = x++ * –y; finally, we are printing the value of x, y, and z in the console.

Note: It is not recommended by Microsoft to use the ++ or — operators inside a complex expression like the above example. The reason is if we use the ++ or — operator on the same variable multiple times in an expression, then we cannot predict the output. So, if you are just incrementing the value of a variable by 1 or decrementing the variable by 1, then in that scenario you need to use these Increment or Decrement Operators. One of the ideal scenarios where you need to use the increment or decrement operator is inside a loop. What is a loop, why loop, and what is a counter variable, we will discuss this in our upcoming articles, but now just have a look at the following example, where I am using the for loop and increment operator?

Ternary Operator in C#:

The above statement means that first, we need to evaluate the condition. If the condition is true the first_expression is executed and becomes the result and if the condition is false, the second_expression is executed and becomes the result.

Example to understand Ternary Operator in C#:

In the next article, I am going to discuss Control Flow Statements  in C# with Examples. Here, in this article, I try to explain Operators in C# with Examples and I hope you enjoy this Operators in C# article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

About the Author: Pranaya Rout

3 thoughts on “Operators in C#”

Leave a reply cancel reply.

C# Assignment Operators

assignment_icon

  • What is C# Assignment Operators?
  • How many types of assignment operators in C sharp?
  • How to use assignment operator in program?

The C# assignment operator is generally suffix with arithmetic operators. The symbol of c sharp assignment operator is "=" without quotes. The assignment operator widely used with C# programming. Consider a simple example:

result=num1+num2;

In this example, the equal to (=) assignment operator assigns the value of num1 + num2 into result variable.

Various types of C# assignment operators are mentioned below:

Assignment Operators:

Assignment Operators Usage Examples
(Equal to) result=5 Assign the value 5 for result
(Plus Equal to) result+=5 Same as result=result+5
(Minus Equal to) result-=5 Same as result=result-5
(Multiply Equal to) result*=5 Same as result=result*5
(Divide Equal to) result/=5 Same as result=result/5
(Modulus Equal to) result%=5 Same as result=result%5

In this chapter, you learned about different types of assignment operators in C# . You also learned how to use these assignment operators in a program. In next chapter, you will learn about Unary Operator in C# .

Share your thought

Complete Csharp Tutorial

Please support us by enabling ads on this page. Refresh YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!   But we have to show ads on our site to keep it free and updated . We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill . Your little contribution will encourage us to regularly update this site.

C# Assignment Operators

SymbolOperationExample
+=Plus Equal Tox+=15 is x=x+15
-=Minus Equal Tox- =15 is x=x-15
*=Multiply Equal Tox*=16 is x=x+16
%=Modulus Equal Tox%=15 is x=x%15
/=Divide Equal Tox/=16 is x=x/16

C# Assignment Operators Example

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

Advertisement

Home » .Net » C# Programs

C# Assignment Operators Example

C# example for assignment operators: Here, we are writing a C# program to demonstrate example of all assignment operators. By IncludeHelp Last updated : April 15, 2023

Assignment Operators

Assignment operators (Assignment ( = ) and compound assignments ( += , -+ , *= , /= , %= )) are used to assign the value or an expression's result to the left side variable, following are the set of assignment operators,

  • "=" – it is used to assign value or an expression's result to the left side variable
  • "+=" – it is used to add second operand to the existing operand's value and assigns it back (a+=b is equal to a=a+b)
  • "-=" – it is used to subtract second operand from the existing operand's value and assigns it back (a-=b is equal to a=a-b)
  • "/=" – it is used to divide second operand from the existing operand's value and assigns it back (a/=b is equal to a=a+b)
  • "*=" – it is used to multiply second operand with the existing operand's value and assigns it back (a*=b is equal to a=a*b)
  • "%=" – it is used to get the remainder by dividing second operand with the existing operand's value and assigns it back (a%=b is equal to a=a%b)

C# code to demonstrate the example of assignment operators

C# Basic Programs »

Related Programs

  • C# program to print messages/text (program to print Hello world)
  • C# program to demonstrate example of Console.Write() and Console.WriteLine()
  • C# program to print a new line
  • C# program to print backslash (\)
  • C# program to demonstrate the example of New keyword
  • C# program to print size of various data types
  • C# program for type conversion from double to int
  • C# program to convert various data type to string using ToString() method
  • C# program to define various types of constants
  • C# program to declare different types of variables, assign the values and print
  • C# program to input and print an integer number
  • C# program to demonstrate example of arithmetic operators
  • C# program to demonstrate example of sizeof() operator
  • C# program to demonstrate example of equal to and not equal to operators
  • C# program to demonstrate example of relational operators
  • C# program to demonstrate example of bitwise operators
  • C# program to find the addition of two integer numbers
  • C# program to swap two numbers with and without using third variable
  • C# | print type, max and min value of various data types
  • C# program to swap numbers using XOR operator
  • C# program to find the magnitude of an integer number
  • C# program to demonstrate the example of the left-shift operator
  • C# program to demonstrate the example of the right shift operator
  • C# program to read the grade of students and print the appropriate description of grade
  • C# program to calculate the size of the area in square-feet based on specified length and width
  • C# program to find the division of exponents of the same base
  • C# program to demonstrate the example goto statement
  • C# program to print a message without using the WriteLine() method
  • C# program to convert a binary number into a decimal number
  • C# program to convert a decimal number into a binary number
  • C# program to convert a decimal number into an octal number
  • C# program to convert a hexadecimal number into a decimal number
  • C# program to convert a decimal number into a hexadecimal number
  • C# program to convert a meter into kilo-meter and vice versa
  • C# program to convert a temperature from Celsius to Fahrenheit
  • C# program to convert a temperature from Fahrenheit into Celsius
  • C# program to create gray code
  • C# program to change the case of entered character
  • C# program to convert entered days into years, weeks, and days

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

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 ==

StevenSwiniarski's avatar

Operators are used to perform various operations on variables and values.

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 .

Operators can be organized into the following groups:

  • Arithmetic operators for performing traditional math evaluations.
  • Assignment operators for assigning values to variables.
  • Comparison operators for comparing two values.
  • Logical operators for combining Boolean values.
  • Bitwise operators for manipulating the bits of a number.

Arithmetic Operators

C# has the following arithmetic operators:

  • Addition, + , returns the sum of two numbers.
  • Subtraction, - , returns the difference between two numbers.
  • Multiplication, * , returns the product of two numbers.
  • Division, / , returns the quotient of two numbers.
  • Modulus, % , returns the remainder of one number divided by another.

The ones above operate on two values. C# also has two unary operators:

  • Increment, ++ , which increments its single operand by one.
  • Decrement, -- , which decrements its single operand by one.

Unlike the other arithmetic operators, the increment and decrement operators change the value of their operand as well as return a value. They also return different results depending on if they precede or follow the operand. Preceding the operand returns the value of the operand before the operation. Following the operand returns the value of the operand after the operation.

Logical Operators

C# has the following logical operators:

  • The & (and) operator returns true if both operands are true .
  • The | (or) operator returns true if either operand is true .
  • The ^ (xor) operator returns true if only one of its operands are true
  • The ! (not) operator returns true if its single operand is false .
Note: & , | , and ^ are logical operators when the operands are bool types. When the operands are numbers they perform bitwise operations. See Bitwise Operators below.

The above operators always evaluate both operands. There are also these conditional “short circuiting” operators:

  • The && (conditional and) operator returns true if both operands are true . If the first operand is false , the second operand is not evaluated.
  • The || (conditional or) operator returns true if either operand is true . If the first operand is true the second operand is not evaluated.

Assignment Operators

C# includes the following assignment operators:

  • The = operator assigns the value on the right to the variable on the left.
  • The += operator updates a variable by incrementing its value and reassigning it.
  • The -= operator updates a variable by decrementing its value and reassigning it.
  • The *= operator updates a variable by multiplying its value and reassigning it.
  • The /= operator updates a variable by dividing its value and reassigning it.
  • The %= operator updates a variable by calculating its modulus against another value and reassigning it.

The assignment operators of the form op= , where op is a binary arithmetic operator, is a shorthand. The expression x = x op y; can be shortened to x op= y; . This compound assignment also works with the logical operators & , | and ^ .

  • The ??= operator assigns the value on the right to the variable on the left if the variable on the left is null .

Comparison Operators

C# has the following comparison operators:

  • Equal, == , for returning true if two values are equal.
  • Not equal, != , for returning true if two values are not equal.
  • Less than, < , for returning true if the left value is less than the right value.
  • Less than or equal to, <= , for returning true if the left value is less than or equal to the right value.
  • Greater than, > , for returning true if the left value is greater than the right value.
  • Greater than or equal to, >= , for returning true if the left value is greater than or equal to the right value.
Note: for these comparison operators, if any operand is not a number ( Double.NaN or Single.NaN ) the result of the operation is false .

Bitwise Operators

C# has the following operators that perform operations on the individual bits of a number.

  • Bitwise complement, ~ , inverts each bit in a number.
  • Left-shift, << , shifts its left operand left by the number of bits specified in its right operand. New right positions are zero-filled.
  • Right-shift, >> , shifts its left operand right by the number of bits specified in its right operand. For signed integers, left positions are filled with the value of the high-order bit. For unsigned integers, left positions are filled with zero.
  • Unsigned right-shift, >>> , same as >> except left positions are always zero-filled.
  • Logical AND, & , performs a bitwise logical AND of its operands.
  • Logical OR, | , performs a bitwise logical OR on its operands.
  • Logical XOR, ^ , performs a bitwise logical XOR on its operands.

All contributors

Contribute to docs.

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn C# on Codecademy

Computer science.

  • C# - Introduction
  • C# - Syntax
  • C# - Comments
  • C# - Data Types
  • C# - Type Casting
  • C# - Operators
  • C# - Strings
  • C# - Booleans
  • C# - If Else
  • C# - Switch
  • C# - While Loop
  • C# - For Loop
  • C# - goto Statement
  • C# - Continue Statement
  • C# - Break Statement
  • C# - Arrays
  • C# - Methods
  • C# - Classes/Objects
  • C# - Constructors
  • C# - Destructors
  • C# - Encapsulation
  • C# - Operator Overloading
  • C# - Inheritance
  • C# - Polymorphism
  • C# - Math Methods
  • C# - String Methods
  • C# - Data Structures
  • C# - Examples
  • C# - Interview Questions

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

C# - assignment operators example

The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • %= Modulo AND assignment operator

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial
  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Assignment Operators in Programming

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in Python
  • Assignment Operators in C#
  • Assignment Operators in JavaScript
  • Application of Assignment Operators

Assignment operators are used in programming to  assign values  to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

OperatorDescriptionExamples
= (Assignment)Assigns the value on the right to the variable on the left.  assigns the value 10 to the variable x.
+= (Addition Assignment)Adds the value on the right to the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
-= (Subtraction Assignment)Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
*= (Multiplication Assignment)Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
/= (Division Assignment)Divides the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
%= (Modulo Assignment)Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable.  is equivalent to 

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Please Login to comment...

Similar reads.

  • Programming
  • How to Underline in Discord
  • How to Block Someone on Discord
  • How to Report Someone on Discord
  • How to add Bots to Discord Servers
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, introduction.

  • Your First C# Program
  • C# Comments
  • C# Variables and (Primitive) Data Types

C# Operators

C# Basic Input and Output

  • C# Expressions, Statements and Blocks

Flow Control

  • C# if, if...else, if...else if and Nested if Statement

C# ternary (? :) Operator

  • C# for loop
  • C# while and do...while loop
  • Nested Loops in C#: for, while, do-while
  • C# break Statement
  • C# continue Statement
  • C# switch Statement
  • C# Multidimensional Array
  • C# Jagged Array
  • C# foreach loop
  • C# Class and Object
  • C# Access Modifiers
  • C# Variable Scope
  • C# Constructor
  • C# this Keyword
  • C# Destructor
  • C# static Keyword
  • C# Inheritance
  • C# abstract class and method
  • C# Nested Class
  • C# Partial Class and Partial Method
  • C# sealed class and method
  • C# interface
  • C# Polymorphism
  • C# Method Overloading
  • C# Constructor Overloading

Exception Handling

  • C# Exception and Its Types
  • C# Exception Handling
  • C# Collections
  • C# ArrayList
  • C# SortedList
  • C# Hashtable
  • C# Dictionary
  • C# Recursion
  • C# Lambda Expression
  • C# Anonymous Types
  • C# Generics
  • C# Iterators
  • C# Delegates
  • C# Indexers
  • C# Regular Expressions

Additional Topics

  • C# Keywords and Identifiers
  • C# Type Conversion

C# Operator Precedence and Associativity

C# Bitwise and Bit Shift Operators

  • C# using Directive
  • C# Preprocessor Directives
  • Namespaces in C# Programming
  • C# Nullable Types
  • C# yield keyword
  • C# Reflection

C# Tutorials

Operators are symbols that are used to perform operations on operands. Operands may be variables and/or constants.

For example , in 2+3 , + is an operator that is used to carry out addition operation, while 2 and 3 are operands.

Operators are used to manipulate variables and values in a program. C# supports a number of operators that are classified based on the type of operations they perform.

1. Basic Assignment Operator

Basic assignment operator (=) is used to assign values to variables. For example,

Here, 50.05 is assigned to x.

Example 1: Basic Assignment Operator

When we run the program, the output will be:

This is a simple example that demonstrates the use of assignment operator.

You might have noticed the use of curly brackets { } in the example. We will discuss about them in string formatting . For now, just keep in mind that {0} is replaced by the first variable that follows the string, {1} is replaced by the second variable and so on.

2. Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc.

For example,

C# Arithmetic Operators
Operator Operator Name Example
+ Addition Operator 6 + 3 evaluates to 9
- Subtraction Operator 10 - 6 evaluates to 4
* Multiplication Operator 4 * 2 evaluates to 8
/ Division Operator 10 / 5 evaluates to 2
% Modulo Operator (Remainder) 16 % 3 evaluates to 1

Example 2: Arithmetic Operators

Arithmetic operations are carried out in the above example. Variables can be replaced by constants in the statements. For example,

3. Relational Operators

Relational operators are used to check the relationship between two operands. If the relationship is true the result will be true , otherwise it will result in false .

Relational operators are used in decision making and loops.

C# Relational Operators
Operator Operator Name Example
== Equal to 6 == 4 evaluates to false
> Greater than 3 > -1 evaluates to true
< Less than 5 < 3 evaluates to false
>= Greater than or equal to 4 >= 4 evaluates to true
<= Less than or equal to 5 <= 3 evaluates to false
!= Not equal to 10 != 2 evaluates to true

Example 3: Relational Operators

4. logical operators.

Logical operators are used to perform logical operation such as and , or . Logical operators operates on boolean expressions ( true and false ) and returns boolean values. Logical operators are used in decision making and loops.

Here is how the result is evaluated for logical AND and OR operators.

C# Logical operators
Operand 1 Operand 2 OR (||) AND (&&)
true true true true
true false true false
false true true false
false false false false

In simple words, the table can be summarized as:

  • If one of the operand is true, the OR operator will evaluate it to true .
  • If one of the operand is false, the AND operator will evaluate it to false .

Example 4: Logical Operators

5. unary operators.

Unlike other operators, the unary operators operates on a single operand.

C# unary operators
Operator Operator Name Description
+ Unary Plus Leaves the sign of operand as it is
- Unary Minus Inverts the sign of operand
++ Increment Increment value by 1
-- Decrement Decrement value by 1
! Logical Negation (Not) Inverts the value of a boolean

Example 5: Unary Operators

The increment (++) and decrement (--) operators can be used as prefix and postfix. If used as prefix, the change in value of variable is seen on the same line and if used as postfix, the change in value of variable is seen on the next line. This will be clear by the example below.

Example 6: Post and Pre Increment operators in C#

We can see the effect of using ++ as prefix and postfix. When ++ is used after the operand, the value is first evaluated and then it is incremented by 1 . Hence the statement

prints 10 instead of 11 . After the value is printed, the value of number is incremented by 1 .

The process is opposite when ++ is used as prefix. The value is incremented before printing. Hence the statement

prints 12 .

The case is same for decrement operator (--) .

6. Ternary Operator

The ternary operator ? : operates on three operands. It is a shorthand for if-then-else statement. Ternary operator can be used as follows:

The ternary operator works as follows:

  • If the expression stated by Condition is true , the result of Expression1 is assigned to variable.
  • If it is false , the result of Expression2 is assigned to variable.

Example 7: Ternary Operator

To learn more, visit C# ternary operator .

7. Bitwise and Bit Shift Operators

Bitwise and bit shift operators are used to perform bit manipulation operations.

C# Bitwise and Bit Shift operators
Operator Operator Name
~ Bitwise Complement
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Bitwise Left Shift
>> Bitwise Right Shift

Example 8: Bitwise and Bit Shift Operator

To learn more, visit C# Bitwise and Bit Shift operator .

8. Compound Assignment Operators

C# Compound Assignment Operators
Operator Operator Name Example Equivalent To
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
%= Modulo Assignment
&= Bitwise AND Assignment
|= Bitwise OR Assignment
^= Bitwise XOR Assignment
<<= Left Shift Assignment
>>= Right Shift Assignment
=> Lambda Operator

Example 9: Compound Assignment Operator

We will discuss about Lambda operators in later tutorial.

Table of Contents

  • Basic Assignment Operator
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Unary Operators
  • Ternary Operator
  • Bitwise and Bit Shift Operators
  • Compound Assignment Operators

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

C# Tutorial

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

What is |= assignment operator? [duplicate]

Possible Duplicate: What is this operator “|=”? How can I implement this in C#?

Can you explain what is the opearator:"|=" ?

For example here how should I read it:

Community's user avatar

3 Answers 3

if _isChanged == true it will stay true

if _isChanged == false it will become the result of _pk_country != value

powerMicha's user avatar

  • 1 So it means it is equivalent to _isChanged || ( _pk_country != value ); –  hungryMind Commented Jul 14, 2011 at 9:16
  • 1 right: _isChanged = _isChanged || ( _pk_country != value ); –  powerMicha Commented Jul 14, 2011 at 9:20

a |= b is simply a shorthand notation for a = a | b. Same goes for the same notation for other operators. In short, you could say something like:

a [operator]= b is equivalent to a = a [operator] b

Erik van Brakel's user avatar

  • 1 What was the reason for downvoting? People on this site make very fast desicions sometimes... It's not just like Like/Dislike of Facebook, even if Facebook doesn't have Dislike option... –  Tigran Commented Jul 14, 2011 at 9:34

Not the answer you're looking for? Browse other questions tagged c# .net binary operators or ask your own question .

  • The Overflow Blog
  • Where developers feel AI coding tools are working—and where they’re missing...
  • He sold his first company for billions. Now he’s building a better developer...
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Should low-scoring meta questions no longer be hidden on the Meta.SO home...
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • In the absence of an agreement addressing the issue, is there any law giving a university copyright in an undergraduate student's class paper?
  • Could a civilisation develop spaceflight by artillery before developing orbit-capable rockets?
  • The answer is not ___
  • If I was ever deported, would it only be to my country of citizenship? Or can I arrange something else?
  • Does the Ring of Mind Shielding need to be attuned to hear a soul inside?
  • Dark setting action fantasy anime; protagonist has white hair, wears black, slim clothes, and fights with his hand
  • What made scientists think that chemistry is reducible to physics and when did that happen?
  • How do Cultivator Colossus and bounce lands interact?
  • Are there any good Jewish books which speak on trauma and emotional pain and then tie in lessons taken from Jewish sources?
  • What is the smallest interval between two palindromic times on a 24-hour digital clock?
  • Can ATmega328P microcontroller work at 3.3 V with 8 MHz oscillator
  • Complexity of computing minimum unsatisfiable core
  • Loop tools Bridge not joining three joined circles with the same vertex count in Blender 4.2
  • Print 4 billion if statements
  • US Visa Appointment error: "Your personal details match a profile which already exists in our database"
  • Why would an escrow/title company not accept ACH payments?
  • According to Trinitarians, how could Jesus (God the Son) be GIVEN life in Himself (John 5:26), if he shares the same essence of being than the Father?
  • How does the size of a resistor affect its power usage?
  • Why is China not mentioned in the Fallout TV series despite its significant role in the games' lore?
  • How can moving observer explain non-simultaneity?
  • What kind of epistemology would justify accepting religious claims that lie beyond the reach of scientific and historical verification?
  • VLA configuration locations
  • Minimal dominating sets in thin hypergraphs
  • Is it even possible to build a beacon to announce we exist?

assignment operator in c# example

This browser is no longer supported.

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

?: operator - the ternary conditional operator

  • 11 contributors

The conditional operator ?: , also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false , as the following example shows:

As the preceding example shows, the syntax for the conditional operator is as follows:

The condition expression must evaluate to true or false . If condition evaluates to true , the consequent expression is evaluated, and its result becomes the result of the operation. If condition evaluates to false , the alternative expression is evaluated, and its result becomes the result of the operation. Only consequent or alternative is evaluated. Conditional expressions are target-typed. That is, if a target type of a conditional expression is known, the types of consequent and alternative must be implicitly convertible to the target type, as the following example shows:

If a target type of a conditional expression is unknown (for example, when you use the var keyword) or the type of consequent and alternative must be the same or there must be an implicit conversion from one type to the other:

The conditional operator is right-associative, that is, an expression of the form

is evaluated as

You can use the following mnemonic device to remember how the conditional operator is evaluated:

Conditional ref expression

A conditional ref expression conditionally returns a variable reference, as the following example shows:

You can ref assign the result of a conditional ref expression, use it as a reference return or pass it as a ref , out , in , or ref readonly method parameter . You can also assign to the result of a conditional ref expression, as the preceding example shows.

The syntax for a conditional ref expression is as follows:

Like the conditional operator, a conditional ref expression evaluates only one of the two expressions: either consequent or alternative .

In a conditional ref expression, the type of consequent and alternative must be the same. Conditional ref expressions aren't target-typed.

Conditional operator and an if statement

Use of the conditional operator instead of an if statement might result in more concise code in cases when you need conditionally to compute a value. The following example demonstrates two ways to classify an integer as negative or nonnegative:

Operator overloadability

A user-defined type can't overload the conditional operator.

C# language specification

For more information, see the Conditional operator section of the C# language specification .

Specifications for newer features are:

  • Target-typed conditional expression
  • Simplify conditional expression (style rule IDE0075)
  • C# operators and expressions
  • if statement
  • ?. and ?[] operators
  • ?? and ??= operators
  • ref keyword

Additional resources

IMAGES

  1. C# Assignment Operators with Examples

    assignment operator in c# example

  2. C# Operators Tutorial

    assignment operator in c# example

  3. C# Assignment Operator

    assignment operator in c# example

  4. C# Operators

    assignment operator in c# example

  5. assignment operator in C# Programming

    assignment operator in c# example

  6. Learn C# Programming

    assignment operator in c# example

VIDEO

  1. Operators In C#

  2. C Assignment Subtraction operator #short #c#assignment #subtraction #operator #printf #coding

  3. assignment operators in c language

  4. 13-Assignment Operator in C#

  5. Programming C# for Beginners Episode-3: Operators

  6. Operators in C language

COMMENTS

  1. 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 implicitly convertible to it.

  2. 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.

  3. C# 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; Try it Yourself ». The addition assignment operator (+=) adds a value to a variable: Example. int x = 10; x += 5;

  4. 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 ...

  5. Operators in C# with Examples

    For example, consider the expression 2 + 3 = 5, here 2 and 3 are operands, and + and = are called operators. So, the Operators in C# are used to manipulate the variables and values in a program. Note: In the above example, x, y, 10, and 20 are called Operands. So, the operand may be variables or values.

  6. ?? and ??= operators

    In expressions with the null-conditional operators ?. and ?[], you can use the ?? operator to provide an alternative expression to evaluate in case the result of the expression with null-conditional operations is null:

  7. 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.

  8. C#

    Different types of assignment operators are shown below: "=" (Simple Assignment): This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.Example: a = 10; b = 20; ch = 'y'; "+=" (Add Assignment): This operator is combination of '+' and '=' operators.

  9. C# Assignment Operators

    The C# assignment operator is generally suffix with arithmetic operators. The symbol of c sharp assignment operator is "=" without quotes. The assignment operator widely used with C# programming. Consider a simple example: result=num1+num2; In this example, the equal to (=) assignment operator assigns the value of num1 + num2 into result variable.

  10. C# Assignment Operators

    The C# Assignment operators are associated with arithmetic operators as a prefix, i.e., +=, -=, *=, /=, %=. The following tables show the available list of C# assignment operators. Symbol

  11. Operators and expressions

    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. ... 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).

  12. C# Assignment Operators Example

    Assignment operators (Assignment (=) and compound assignments (+=, -+, *=, /=, %=)) are used to assign the value or an expression's result to the left side variable, following are the set of assignment operators, "=" - it is used to assign value or an expression's result to the left side variable. "+=" - it is used to add second operand to ...

  13. How to Overload Assignment Operator in C#

    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.. Use Implicit Conversion Operators to Implement Assignment Operator Overloading in C#. You can achieve assignment overloading by using implicit conversion operators.

  14. 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;

  15. C# assignment operators example

    The example below shows the usage of assignment and compound assignment operators: = Assignment operator. += Addition AND assignment operator. -= Subtraction AND assignment operator. *= Multiply AND assignment operator. /= Division AND assignment operator. %= Modulo AND assignment operator. using System; class MyProgram { static void Main ...

  16. Null-Coalescing Assignment Operator in C# 8.0

    Filtering operators are those operators which are used to filter the data according to the user requirement from the given data source or from the given sequence. For example, in an employee record, we want to get the data of the employees whose age in 21. So, we filter the record, according to their age. In LINQ, you can filter using the following

  17. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  18. C# Operators: Arithmetic, Comparison, Logical and more.

    Operators are used to manipulate variables and values in a program. C# supports a number of operators that are classified based on the type of operations they perform. 1. Basic Assignment Operator. Basic assignment operator (=) is used to assign values to variables. For example, double x; x = 50.05; Here, 50.05 is assigned to x.

  19. c#

    What was the reason for downvoting? People on this site make very fast desicions sometimes... It's not just like Like/Dislike of Facebook, even if Facebook doesn't have Dislike option...

  20. Bitwise and shift operators (C# reference)

    Unsigned right-shift operator >>> Available in C# 11 and later, the >>> operator shifts its left-hand operand right by the number of bits defined by its right-hand operand. For information about how the right-hand operand defines the shift count, see the Shift count of the shift operators section.. The >>> operator always performs a logical shift. That is, the high-order empty bit positions ...

  21. ?: operator

    In this article. The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false, as the following example shows:. string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ?