This browser is no longer supported.

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

Assignment operators (C# reference)

  • 11 contributors

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.

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

is evaluated as

The following example demonstrates the usage of the assignment operator with a local variable, a property, and an indexer element as its left-hand operand:

The left-hand operand of an assignment receives the value of the right-hand operand. When the operands are of value types , assignment copies the contents of the right-hand operand. When the operands are of reference types , assignment copies the reference to the object.

This is called value assignment : the value is assigned.

ref assignment

Ref assignment = ref makes its left-hand operand an alias to the right-hand operand, as the following example demonstrates:

In the preceding example, the local reference variable arrayElement is initialized as an alias to the first array element. Then, it's ref reassigned to refer to the last array element. As it's an alias, when you update its value with an ordinary assignment operator = , the corresponding array element is also updated.

The left-hand operand of ref assignment can be a local reference variable , a ref field , and a ref , out , or in method parameter. Both operands must be of the same type.

Compound assignment

For a binary operator op , a compound assignment expression of the form

is equivalent to

except that x is only evaluated once.

Compound assignment is supported by arithmetic , Boolean logical , and bitwise logical and shift operators.

Null-coalescing assignment

You can use the null-coalescing assignment operator ??= to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . For more information, see the ?? and ??= operators article.

Operator overloadability

A user-defined type can't overload the assignment operator. However, a user-defined type can define an implicit conversion to another type. That way, the value of a user-defined type can be assigned to a variable, a property, or an indexer element of another type. For more information, see User-defined conversion operators .

A user-defined type can't explicitly overload a compound assignment operator. However, if a user-defined type overloads a binary operator op , the op= operator, if it exists, is also implicitly overloaded.

C# language specification

For more information, see the Assignment operators section of the C# language specification .

  • C# operators and expressions
  • ref keyword
  • Use compound assignment (style rules IDE0054 and IDE0074)

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

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 −

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

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

custom assignment operator c#

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

custom assignment operator c#

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Visual Basic questions
  • View Python questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

custom assignment operator c#

A Beginner's Tutorial on Operator Overloading in C#

custom assignment operator c#

  • Download demo - 9.7 KB

Introduction

This article discusses operator overloading in C#. What are the various types of operators that can be overloaded? We will create a small dummy application to see how we can overload some basic operators.

In an object oriented programming language like C#, operator overloading provides a much more natural way of implementing the operations on custom types. Suppose we have a class created for Complex number and we want to perform all the arithmetic operations on this type. One way to do this is by having functions like Add , Subtract inside the class and have the functionality. Another way is to actually have the overloaded version of operators to act on this type.

Operator overloading provides a much natural abstraction for the types. When we think about possible operation on some data type, we can think of binary operators, unary operators, relational operators and perhaps some conversion operations to and from the basic types. In C#, achieving all this is possible using operator overloading.

Using the Code

Before looking at the implementation details, let's see what are the conventions that need to be followed if we want to overload an operator.

  • The operator function should be a member function of the containing type.
  • The operator function must be static .
  • The operator function must have the keyword operator followed by the operator to be overridden.
  • The arguments of the function are the operands.
  • The return value of the function is the result of the operation.

So to understand the above mentioned points more clearly, we can visualize the operators getting invoked as function calls (below code will not compile, it is only for understanding purposes).

So following the above guidelines, let us see how we can implement operator overloading. We will create a small class Rational representing a rational number and will implement some basic overloaded operators in it.

Overloading the Binary Operators

Binary operators function will take two arguments and return a new object of the Containing type. Let us try to implement the binary operator + for our Rational class.

Once we have the binary operator overloaded, we can use it simply as:

The important thing to note here is that once we have the binary operator + implemented, the compound assignment operator for that operator, i.e.,  += in this case also gets implemented in terms of this operator, i.e.,  + in this case.

The other possibility could be that we may want to have mix mode arithmetic with our type, i.e., we may want to have the arithmetic operations to work with our Rational type and some primitive type. So if we want to have the possibility of having Rational + int , then we will have to implement an overloaded function for that too.

Overloading the Unary Operators

To overload the unary operators, we need a function taking only one argument of the containing type. The important thing in case of overloading unary operators is that we should not create a new object but instead change the value of the object being passed to us and return it. Let us implement the unary ++ for our Rational type now.

The thing to notice in the above code snippet is that we overloaded ++ and C# internally took care of using it in pre-increment and post-increment scenario. So unlike C++, we need not implement the separate versions for prefix and post-fix unary operators.

Overloading the Relational Operators

Relational operators like < and > can also be overloaded as functions taking two arguments. The important thing to note is that we need to overload relational operators in pairs, i.e., if I am overloading < operator, than I will have to overload > operator too. Same is true for (<=, >=) and (==, !=) operators. So let us go ahead and implement the relational operators in our Rational class.

Other important thing to note is while implementing the equality, i.e.,  == operator. If we are overloading == operator, then we need to implement != operator too (as discussed above). Also, we need to override the Equals and GetHashCode functions so that if our object returns true for == , then it should return true for Equals function too and should return the same value from GetHashCode() .

Overloading the Conversion Operators

We might also need to implement conversion operators sometimes so that our type can safely be converted to and from other types. We can define the conversion operators as implicit or explicit . In case of implicit conversion, the user will not have to explicitly type cast our type to target type and our conversion operation will work. In case of explicit conversion, the user will have to explicitly cast our type to target type to invoke our conversion operation. If the casting is not performed, it will give a compile time error.

Let us go ahead and define the conversion operation for our Rational type. We will implicitly convert integer types to Rational type, but we will keep the conversion from Rational to double explicit.

Now we have some basic operators overloaded/implemented for this Rational class. We have implemented some of the operators in each category of operators, rest of the operators can be overloaded on same lines.

Note : Please refer to the attached sample code to see the complete class with sample test code.

Point of Interest

This article is written as a walk-through tutorial on operator overloading in C# from a beginner's perspective. Most of the veteran programmers are already aware of this basic stuff and find the information mundane, still I hope this has been informative.

  • 4 th September, 2012: First version

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com [ ^ ]

  • Microsoft MVP 2015

Twitter

Comments and Discussions

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

custom assignment operator c#

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

Dot Net Tutorials

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

Note: In the above example, x, y, 10, and 20 are called Operands. So, the operand may be variables or values.

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
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Unary Operators or
  • Ternary Operator or Conditional Operator

In C#, the Operators can also be categorized based on the Number of Operands:

  • Unary Operator : The Operator that requires one operand (variable or value) to perform the operation is called Unary Operator.
  • Binary Operator : Then Operator that requires two operands (variables or values) to perform the operation is called Binary Operator.
  • Ternary Operator : The Operator that requires three operands (variables or values) to perform the operation is called Ternary Operator. The Ternary Operator is also called Conditional Operator.

For a better understanding of the different types of operators supported in C# Programming Language, please have a look at the below image. 

Types of Operators in C#

Arithmetic Operators in C#

The Arithmetic Operators in C# are used to perform arithmetic/mathematical operations like addition, subtraction, multiplication, division, etc. on operands. The following Operators are falling into this category. 

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

Division Operator (/): The / (Division) operator divides two operands. As this operator works with two operands, so, this / (Division) operator belongs to the category of the binary operator. The Division Operator divides 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; //2, Here, it will divide 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 below example, I am showing how to use Arithmetic Operators with Operand which are variables. Here, Num1 and Num2 are variables and all the Arithmetic Operators are working on these two variables.

Arithmetic Operators in C# with Examples

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.

Note: The point that you need to remember is that the operator working on the operands and the operand may be variables, or values and can also be the combination of both.

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 (=):

This operator is used to assign the value of the right-hand side operand to the left-hand side operand i.e. to a variable.  For example: int a=10; int b=20; char ch = ‘a’; a=a+4; //(a=10+4) b=b-4; //(b=20-4)

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 (*=):

This operator is the combination of * and = operators. It is used to multiply 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)

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

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 (!=):

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

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 (>):

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

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

Example to Understand Relational Operators in C#

Logical Operators in C#:

The Logical Operators are mainly used in conditional statements and loops for evaluating a condition. These operators are going to work with boolean expressions. The different types of Logical Operators supported in C# are as follows:

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 (!):

This operator is used to return true if the condition in the expression is not satisfied. Otherwise, it will return false. For example, !a returns true if a is false.

Example to Understand Logical Operators in C#:

Example to Understand Logical Operators in C#

Bitwise Operators in C#:

The Bitwise Operators in C# perform bit-by-bit processing. They can be used with any of the integer (short, int, long, ushort, uint, ulong, byte) types. The different types of Bitwise Operators supported in C# are as follows.

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 (^):

The bitwise OR operator is represented by ^. This operator performs a bitwise XOR operation on the corresponding bits of two operands. If the corresponding bits are different, it gives 1. If the corresponding bits are the same, it gives 0. For example, int a=12, b=25; int result = a^b; //21 How? 12 Binary Number: 00001100 25 Binary Number: 00011001 Bitwise AND operation between 12 and 25: 00001100 00011001 ======== 00010101 (it is 21 in decimal)

Example to Understand Bitwise Operators in C#:

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.

Bitwise Operators in C#

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 operators (++): Example: (++x, x++)
  • Decrement operators (–): Example: (–x, x–)

Increment Operator (++) in C# Language:

The Increment Operator (++) is a unary operator. It operates on a single operand only. Again, it is classified into two types:

  • Post-Increment Operator
  • Pre-Increment Operator

Post Increment Operators:

The Post Increment Operators are the operators that are used as a suffix to its variable. It is placed after the variable. For example, a++ will also increase the value of the variable a by 1.

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

Pre-Increment Operators:

The Pre-Increment Operators are the operators which are used as a prefix to its variable. It is placed before the variable. For example, ++a will increase the value of the variable a by 1.

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

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 Operator
  • Pre-Decrement Operator

Post Decrement Operators:

The Post Decrement Operators are the operators that are used as a suffix to its variable. It is placed after the variable. For example, a– will also decrease the value of the variable a by 1.

Syntax:  Variable–; Example:   x–;

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.

Syntax:   –Variable; Example: — x;

Unary Operators in C#

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 Increment Operators in C# Language

Example to understand Decrement 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.

Five Steps to Understand How the Unary Operators Works in C#?

  • Step 1: If there is some pre-increment or pre-decrement in the expression, that should execute first.
  • Step 2: The second step is to substitute the values in the expression.
  • Step 3: In the third step we need to evaluate the expression.
  • Step 4: I n the fourth step Assignment needs to be performed.
  • Step 5: The final step is to perform post-increment or post-decrement.

Now, if you have still doubt about the above five steps, then don’t worry we will see some examples to understand this step in a better way.

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.

Let us evaluate the expression  z = x++ * –y;  by following the above 5 steps:

  • The First step is Pre-Increment or Pre-Decrement . Is there any pre-increment or pre-decrement in the expression? There is no pre-increment but there is a pre-decrement in the expression i.e. –y. So, execute that pre-decrement operator which will decrease the value of y by 1 i.e. now y becomes 19.
  • The second step is Substitution . So, substitute the values of x and y. That means x will be substituted by 10 and y will be substituted by 19.
  • The third step is Evaluation . So, evaluate the expression i.e. 10 * 19 = 190.
  • The fourth step is the Assignment . So, assign the evaluated value to the given variable i.e. 190 will be assigned to z. So, now the z value becomes 190.
  • The last step is Post-Increment and Post-Decrement . Is there any post-increment or post-decrement in the expression? There is no post-decrement but there is a post-increment in the expression i.e. x++. So, execute that post-increment which will increase the value of x by 1 i.e. x becomes 11.

So, when you will execute the above program it will print the x, y, and z values as 11, 19, and 190 respectively.

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 Ternary Operator in C# is also known as the Conditional Operator ( ?: ). It is actually the shorthand of the if-else statement. It is called ternary because it has three operands or arguments. The first argument is a comparison argument, the second is the result of a true comparison, and the third is the result of a false comparison.

Syntax: Condition? first_expression : second_expression;

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

Output: Result = 20

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.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

2 thoughts on “Operators in C#”

custom assignment operator c#

Hi Sir.. just noticed.. plz correct result of ternary operator is as 20..

custom assignment operator c#

Very clear and concise. Never seen like this before.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

MarketSplash

CSharp Operator: Correct Usage

CSharp operators are the building blocks of any program, enabling data manipulation and flow control. This article explores the different types of operators - arithmetic, relational, logical, assignment, and bitwise - with practical examples to enhance your coding skills.

💡 KEY INSIGHTS

  • C# 6.0's null-conditional operators significantly enhance code efficiency and reliability, especially in complex object traversal scenarios, by minimizing the risk of NullReferenceException.
  • The article emphasizes the versatility of bitwise operators in C#, which are crucial for tasks like encryption and embedded systems programming, demonstrating their advanced applications beyond basic arithmetic.
  • Logical operators in C#, such as AND, OR, and NOT, are pivotal for controlling program flow based on multiple conditions, highlighting their role in complex decision-making processes.
  • The use of relational operators for value comparison in C# is not just fundamental but also a key skill, as it underpins the logic for numerous control structures and algorithms.

CSharp operators are fundamental to writing efficient and effective code. They allow us to perform operations on variables and values, influencing how our programs behave.

This article will provide a clear, in-depth look at these essential tools, enhancing your coding skills and knowledge.

custom assignment operator c#

Understanding CSharp Operators

Using arithmetic operators in csharp, relational operators in csharp, logical operators in csharp, assignment operators in csharp, bitwise operators in csharp, frequently asked questions.

CSharp operators are the building blocks of any CSharp program. They allow us to manipulate data and make decisions based on certain conditions.

There are several types of operators in CSharp. These include arithmetic operators , relational operators , logical operators , assignment operators , and bitwise operators .

Understanding these operators is crucial for writing efficient and effective code.

custom assignment operator c#

Addition Operator

Subtraction operator, multiplication operator, division operator, modulus operator.

Arithmetic operators in CSharp are used to perform mathematical operations such as addition, subtraction, multiplication, and division. They are fundamental to any programming language and are used frequently in coding.

The addition operator (+) adds two numbers together. For example:

The subtraction operator (-) subtracts one number from another. Here's how you can use it:

The multiplication operator (*) multiplies two numbers. For instance:

The division operator (/) divides one number by another. It's important to note that if both numbers are integers, the result will also be an integer. Here's an example:

The modulus operator (%) returns the remainder of a division operation. For example:

Understanding and using these arithmetic operators effectively is a key skill in CSharp programming. They allow you to perform basic mathematical operations on your data, which is a common requirement in many programming tasks.

Greater Than Operator

Less than operator, equal to operator, not equal to operator, greater than or equal to operator, less than or equal to operator.

Relational operators in CSharp are used to compare two values or expressions. They return a boolean value, either true or false, based on the result of the comparison.

The greater than operator (>) checks if the value on the left is greater than the value on the right. Here's an example:

The less than operator (<) checks if the value on the left is less than the value on the right. For instance:

The equal to operator (==) checks if the value on the left is equal to the value on the right. Here's how you can use it:

The not equal to operator (!=) checks if the value on the left is not equal to the value on the right. For example:

The greater than or equal to operator (>=) checks if the value on the left is greater than or equal to the value on the right. Here's an example:

The less than or equal to operator (<=) checks if the value on the left is less than or equal to the value on the right. For instance:

If you want to find out more about CSharp dictionary, have a look at this:

custom assignment operator c#

AND Operator

Or operator, not operator.

Logical operators in CSharp are used to combine two or more conditions. They are essential for controlling the flow of your programs based on multiple conditions.

The AND operator (&&) returns true if both the conditions are true. Here's an example:

The OR operator (||) returns true if at least one of the conditions is true. For instance:

The NOT operator (!) reverses the result of the condition. Here's how you can use it:

Understanding and using these logical operators effectively is a key skill in CSharp programming.

They allow you to make decisions and control the flow of your program based on multiple conditions.

This is particularly useful in complex programs where multiple factors can influence the outcome of an operation.

Equals Operator

Addition assignment operator, subtraction assignment operator, multiplication assignment operator, division assignment operator.

Assignment operators in CSharp are used to assign values to variables.

The equals operator (=) assigns the value on the right to the variable on the left. Here's an example:

The addition assignment operator (+=) adds the value on the right to the variable on the left and then assigns the result to the variable on the left. For instance:

The subtraction assignment operator (-=) subtracts the value on the right from the variable on the left and then assigns the result to the variable on the left. Here's how you can use it:

The multiplication assignment operator (*=) multiplies the variable on the left by the value on the right and then assigns the result to the variable on the left. For example:

The division assignment operator (/=) divides the variable on the left by the value on the right and then assigns the result to the variable on the left. Here's an example:

Bitwise AND Operator

Bitwise or operator, bitwise xor operator, bitwise not operator, bitwise shift operators.

Bitwise operators in CSharp are used to perform operations on the binary representations of numbers. They are a bit more advanced than the other operators we've discussed, but they can be very useful in certain situations.

The bitwise AND operator (&) performs a binary AND operation on the bits of two integers. Here's an example:

The bitwise OR operator (|) performs a binary OR operation on the bits of two integers. For instance:

The bitwise XOR operator (^) performs a binary XOR operation on the bits of two integers. Here's how you can use it:

The bitwise NOT operator (~) flips the bits of an integer. For example:

The bitwise shift operators (<< and >>) shift the bits of an integer to the left or right. Here's an example:

By grasping these CSharp operators and their applications, you will be able to code more efficiently and enhance your CSharp programming capabilities significantly.

What Are CSharp Operators?

CSharp operators are symbols that are used to perform operations on variables and values. They include arithmetic, relational, logical, assignment, and bitwise operators.

When Should I Use Bitwise Operators In CSharp?

Bitwise operators are used when you need to manipulate individual bits of a number, which is common in tasks such as encryption, compression, graphics, communications over ports/sockets, embedded systems programming, etc.

What Are Logical Operators In CSharp?

Logical operators in CSharp are used to combine two or more conditions. They include AND (&&), OR (||), and NOT (!).

Let's see what you learned!

What Does The Bitwise AND Operator Do In CSharp?

Continue learning with these csharp guides.

  • UnityScript Vs CSharp: Differences And Best Practices
  • CSharp Bool VS Boolean: Choosing The Right Type
  • CSharp Threadpool Vs Thread: Differences And Usage
  • CSharp Class Vs Interface And Its Application
  • Insight CSharp Equal Vs Equivalent: How To Use It

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

IMAGES

  1. C# Assignment Operator

    custom assignment operator c#

  2. [100% Working Code]

    custom assignment operator c#

  3. assignment operator in C# Programming

    custom assignment operator c#

  4. Assignment Operators in C

    custom assignment operator c#

  5. Assignment Operators in C++

    custom assignment operator c#

  6. C# Assignment Operators

    custom assignment operator c#

VIDEO

  1. Operators in C language

  2. SCORE Academy Physical Science Custom 5 Instructions

  3. #20 Assignment Operators in C#

  4. Assignment final C#

  5. C-017 Updating Assignment Operators In C

  6. This C# Operator Can Help You Write Better Code

COMMENTS

  1. Assignment operators

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

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

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

  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. C# Operator Overloading: A Comprehensive Dive from ...

    Operator overloading, while a somewhat controversial feature in some programming languages, offers a way to provide intuitive interfaces, especially when building custom data types. In C#, operator…

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

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

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

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

  10. A Beginner's Tutorial on Operator Overloading in C#

    Once we have the binary operator overloaded, we can use it simply as: C#. Rational r1 = new Rational( 3, 2 ); Rational r2 = new Rational( 2, 3 ); Rational result = null ; // Testing + operator on types. result = r1 + r2; The important thing to note here is that once we have the binary operator + implemented, the compound assignment operator for ...

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

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

  13. Operators in C# with Examples

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

  14. In C#, How can I create or overload an assignment operator to possibly

    A. Overload the = operator so it will automatically check for a property which is a boolean and has "Specified" concatenated to the current property's name. If such a property exists, it will be assigned true when the value is assigned; if not, then assignment will operate as normal.

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

  16. CSharp Operator: Correct Usage

    CSharp operators are the building blocks of any CSharp program. They allow us to manipulate data and make decisions based on certain conditions. There are several types of operators in CSharp. These include arithmetic operators, relational operators, logical operators, assignment operators, and bitwise operators. Operator Type.

  17. c#

    However, if you want to keep it as a struct, I'd recommend something like this instead: 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 ...

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