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.

C# operator

last modified July 5, 2023

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.

CategorySymbol
Sign operators
Arithmetic
Logical (boolean and bitwise)
String concatenation
Increment, decrement
Shift
Relational
Assignment
Member access
Indexing
Cast
Ternary
Delegate concatenation and removal
Object creation
Type information
Overflow exception control
Indirection and address
Lambda

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

The above two pairs of expressions do the same.

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

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

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.

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 .

C# concatenating strings

The + operator is also used to concatenate strings.

C# arithmetic operators

SymbolName
Addition
Subtraction
Multiplication
/Division
Remainder

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

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.

C# Boolean operators

SymbolName
logical and
logical or
negation

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.

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

Three of four expressions result in true.

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.

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.

SymbolMeaning
less than
less than or equal to
greater than
greater than or equal to
equal to
not equal to

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

SymbolMeaning
bitwise negation
bitwise exclusive or
bitwise and
bitwise or

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

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

C# compound assignment operators

The compound assignment operators consist of two operators. They are shorthand 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; .

C# new operator

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

C# access operator

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

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

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

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

C# type information

We use the sizeof and typeof operators.

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.

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.

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

C# operator precedence

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

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

Operator(s)CategoryAssociativity
Primary Left
Unary Left
Multiplicative Left
Additive Left
Shift Left
Equality Right
Logical AND Left
Logical XOR Left
Logical OR Left
Conditional AND Left
Conditional OR Left
Null Coalescing Left
Ternary Right
Assignment Right

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

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

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

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.

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

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

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.

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.

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.

C# Lambda operator

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.

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.

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

C# calculating 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.

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.

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 .

  • 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
  • iOS 18 Is Out Now: Best New Features and How to Install iOS 18
  • Best External Hard Drives for Mac in 2024: Top Picks for MacBook Pro, MacBook Air & More
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • 10 Best PrimeWire Alternatives (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

C#.NET Tutorials For Beginners and Professionals

C#.NET Tutorials For Beginners and Professionals

In this C#.NET tutorial For Beginners and Professionals article series, we covered all the basic and advanced concepts of C#.NET. In this C# Tutorials For Beginners and Professionals course. I will explain C# language using different types of .NET applications, including the Console ,  Windows ,  ASP.NET MVC ,  ASP.NET Web API ,  ASP.NET Core MVC , and  ASP.NET Core Web API , by taking some real-time scenarios.

These C# Tutorials are for Whom?

These C#.NET tutorials are designed for beginners and professional developers who want to learn C# step by step, from the very basic to the advanced concept, using real-time examples. These tutorials provide a hands-on approach to the subject with step-by-step program examples that will assist you in learning and putting the acquired knowledge into practice.

What is C#.NET?

C# is just a simple, secure, robust, portable, platform-independent, architectural neutral, multithreaded, object-oriented programming language with a strong type exception handling mechanism for developing different kinds of applications such as Web, Windows Form, Console, Web Services, Mobile Apps, etc.

Types of Applications Developed using C#:

With the help of the C# programming language, we can develop different types of secured and robust applications:

What will you Learn From These C#.NET Tutorials?

Prerequisites to learn c#.net.

No Prerequisites are required as we will start from the very basics. But if you have some basic programming knowledge, then it is an added advantage.

Note : If we missed any topics in this C# Tutorials, please let us know by commenting in the Comment Box. We promise to publish articles on those topics as soon as possible. 

Course Information

Course instructor, online training, c#.net online training program, asp.net core training, microservices online training, introduction & environment setup, how computer works, introduction to programming languages, how computer programs works, different types of applications, programming methodologies, algorithm, pseudocode, programs, and flowcharts, introduction to .net framework, .net framework architecture and components, introduction to c# programming language, how to download and install visual studio on windows, creating first console application using visual studio, .net developer roadmap for 2024, coding standard best practices, c#.net basics, basic structure of c# program, methods and properties of console class in c#, data types in c#, literals in c#, type casting in c#, variables in c#, operators in c#, control flow statements in c#, if-else statements in c#, switch statements in c#, loops in c#, while loop in c#, do while loop in c#, for loop in c#, break statement in c#, continue statement in c#, goto statement in c#, functions in c#, user-defined functions in c#, call by value and call by reference in c#, recursion in c#, user input and output in c#, command line arguments in c#, string in c#, static keyword in c#, static vs non-static members in c#, const and read-only in c#, properties in c#, why we should override tostring method in c#, override equals method in c#, difference between convert.tostring and tostring method in c#, checked and unchecked keywords in c#, stack and heap memory in .net, boxing and unboxing in c#, object oriented programming (oops) in c#, class and objects in c#, constructors in c#, types of constructors in c#, why we need constructors in c#, static vs non-static constructors in c#, private constructors in c#, destructors in c#, garbage collection in .net framework, differences between finalize and dispose in c#, access specifiers in c#, encapsulation in c#, abstraction in c#, inheritance in c#, types of inheritance in c#, how to use inheritance in application development, isa and hasa relationship in c#, generalization and specialization in c#, abstract class and abstract methods in c#, abstract class and abstract methods interview questions in c#, how to use abstract classes and methods in c# application, interface in c#, interface interview questions and answers in c#, interface realtime examples in c#, multiple inheritance in c#, multiple inheritance realtime example in c#, polymorphism in c#, method overloading in c#, operator overloading in c#, method overriding in c#, method hiding in c#, partial class and partial methods in c#, sealed class and sealed methods in c#, extension methods in c#, static class in c#, variable reference and instance of a class in c#, oops real-time examples, real-time examples of encapsulation principle in c#, real-time examples of abstraction principle in c#, real-time examples of inheritance principle in c#, real-time examples of polymorphism principle in c#, real-time examples of interface in c#, real-time examples of abstract class in c#, exception handling, exception handling in c#, multiple catch blocks in c#, finally block in c#, how to create custom exceptions in c#, inner exception in c#, exception handling abuse in c#, events, delegates and lambda expression in c#, course structure of events, delegates and lambda expression, roles of events, delegates and event handler in c#, delegates in c#, multicast delegates in c#, delegates real-time example in c#, generic delegates in c#, anonymous method in c#, lambda expressions in c#, events in c# with examples, multi-threading, multithreading in c#, thread class in c#, how to pass data to thread function in type safe manner in c#, how to retrieve data from a thread function in c#, join method and isalive property of thread class in c# , thread synchronization in c#, monitor class in c#, mutex class in c#, semaphore class in c#, semaphoreslim class in c#, deadlock in c#, performance testing of a multithreaded application, thread pool in c#, foreground and background threads in c#, autoresetevent and manualresetevent in c#, thread life cycle in c#, threads priorities in c#, how to terminate a thread in c#, inter thread communication in c#, how to debug a multi-threaded application in c#, collections in c#, arrays in c#, 2d arrays in c#, advantages and disadvantages of arrays in c#, arraylist in c#, hashtable in c#, non-generic stack in c#, non-generic queue in c#, non-generic sortedlist in c#, advantages and disadvantages of non-generic collection in c#, generic collections in c#, generics in c#, generic constraints in c#, generic list collection in c#, how to sort a list of complex type in c#, comparison delegate in c#, dictionary collection class in c#, conversion between array list and dictionary in c#, list vs dictionary in c#, generic stack collection class in c#, generic queue collection class in c#, foreach loop in c#, generic hashset collection class in c#, generic sortedlist collection class in c#, generic sortedset collection class in c#, generic sorteddictionary collection class in c#, generic linkedlist collection class in c#, concurrent collection in c#, concurrentdictionary collection class in c#, concurrentqueue collection class in c#, concurrentstack collection class in c#, concurrentbag collection class in c#, blockingcollection in c#, file handling, file handling in c#, filestream class in c#, streamreader and streamwriter in c#, file class in c#, textwriter and textreader in c#, binarywriter and binaryreader in c#, stringwriter and stringreader in c#, fileinfo class in c#, directoryinfo class in c#, export and import excel data in c#, asynchronous programming, introduction to concurrency, async and await in c#, how to return a value from task in c#, how to execute multiple tasks in c#, how to limit number of concurrent tasks in c#, how to cancel a task in c# using cancellation token, how to create synchronous method using task in c#, retry pattern in c#, only one pattern in c#, how to control the result of a task in c#, task-based asynchronous programming in c#, chaining tasks by using continuation tasks, how to attached child tasks to a parent task in c#, valuetask in c#, how to cancel a non-cancellable task in c#, asynchronous streams in c#, how to cancel asynchronous stream in c#, parallel programming, task parallel library in c#, parallel for in c#, parallel foreach loop in c#, parallel invoke in c#, maximum degree of parallelism in c#, how to cancel parallel operations in c#, atomic methods thread safety and race conditions in c#, interlocked vs lock in c#, parallel linq in c#, multithreading vs asynchronous programming vs parallel programming in c#, automapper in c#, automapper complex mapping in c#, how to map complex type to primitive type using automapper in c#, automapper reverse mapping in c#, automapper conditional mapping in c#, automapper ignore method in c#, fixed and dynamic values in destination property in automapper, optional parameter, indexers and enums, how to make optional parameters in c#, indexers in c#, indexers real-time example in c#, enums in c#, .net framework architecture, dot net framework, common language runtime in .net framework, .net program execution process, intermediate language (ildasm & ilasm) code in c#, common type system in .net framework, common language specification in .net framework, managed and unmanaged code in .net framework, assembly dll exe in .net framework, app domain in .net framework, strong and weak assemblies in .net framework, how to install an assembly into gac in .net framework, dll hell problem and solution in .net framework, var, dynamic and reflection, reflection in c#, dynamic type in c#, var keyword in c#, var vs dynamic in c#, dynamic vs reflection in c#, volatile keyword in c#, ref vs out in c#, named parameters in c#, c# 7.x new features, c# 7 new features, enhancement in out variables in c# 7, pattern matching in c#, digit separators in c# 7, tuples in c# 7, splitting tuples in c# 7, local functions in c# 7, ref returns and ref locals in c# 7, generalized async return types in c# 7, expression bodied members in c#, thrown expression in c#, async main in c#, c# 8 new features, readonly structs in c#, default interface methods in c#, using declarations in c#, static local functions in c#, disposable ref structs in c#, nullable reference types in c# 8, asynchronous disposable in c#, indices and ranges in c#, null-coalescing assignment operator in c#, unmanaged constructed types in c#, stackalloc in in c#, most popular c# books, most recommended c# books, most recommended data structure and algorithms books using c#, 64 thoughts on “c#.net tutorials for beginners and professionals”, leave a reply cancel reply.

This browser is no longer supported.

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

Boolean logical operators - AND, OR, NOT, XOR

  • 5 contributors

The logical Boolean operators perform logical operations with bool operands. The operators include the unary logical negation ( ! ), binary logical AND ( & ), OR ( | ), and exclusive OR ( ^ ), and the binary conditional logical AND ( && ) and OR ( || ).

  • Unary ! (logical negation) operator.
  • Binary & (logical AND) , | (logical OR) , and ^ (logical exclusive OR) operators. Those operators always evaluate both operands.
  • Binary && (conditional logical AND) and || (conditional logical OR) operators. Those operators evaluate the right-hand operand only if it's necessary.

For operands of the integral numeric types , the & , | , and ^ operators perform bitwise logical operations. For more information, see Bitwise and shift operators .

  • Logical negation operator !

The unary prefix ! operator computes logical negation of its operand. That is, it produces true , if the operand evaluates to false , and false , if the operand evaluates to true :

The unary postfix ! operator is the null-forgiving operator .

  • Logical AND operator &

The & operator computes the logical AND of its operands. The result of x & y is true if both x and y evaluate to true . Otherwise, the result is false .

The & operator always evaluates both operands. When the left-hand operand evaluates to false , the operation result is false regardless of the value of the right-hand operand. However, even then, the right-hand operand is evaluated.

In the following example, the right-hand operand of the & operator is a method call, which is performed regardless of the value of the left-hand operand:

The conditional logical AND operator && also computes the logical AND of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to false .

For operands of the integral numeric types , the & operator computes the bitwise logical AND of its operands. The unary & operator is the address-of operator .

  • Logical exclusive OR operator ^

The ^ operator computes the logical exclusive OR, also known as the logical XOR, of its operands. The result of x ^ y is true if x evaluates to true and y evaluates to false , or x evaluates to false and y evaluates to true . Otherwise, the result is false . That is, for the bool operands, the ^ operator computes the same result as the inequality operator != .

For operands of the integral numeric types , the ^ operator computes the bitwise logical exclusive OR of its operands.

  • Logical OR operator |

The | operator computes the logical OR of its operands. The result of x | y is true if either x or y evaluates to true . Otherwise, the result is false .

The | operator always evaluates both operands. When the left-hand operand evaluates to true , the operation result is true regardless of the value of the right-hand operand. However, even then, the right-hand operand is evaluated.

In the following example, the right-hand operand of the | operator is a method call, which is performed regardless of the value of the left-hand operand:

The conditional logical OR operator || also computes the logical OR of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to true .

For operands of the integral numeric types , the | operator computes the bitwise logical OR of its operands.

  • Conditional logical AND operator &&

The conditional logical AND operator && , also known as the "short-circuiting" logical AND operator, computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true . Otherwise, the result is false . If x evaluates to false , y isn't evaluated.

In the following example, the right-hand operand of the && operator is a method call, which isn't performed if the left-hand operand evaluates to false :

The logical AND operator & also computes the logical AND of its operands, but always evaluates both operands.

  • Conditional logical OR operator ||

The conditional logical OR operator || , also known as the "short-circuiting" logical OR operator, computes the logical OR of its operands. The result of x || y is true if either x or y evaluates to true . Otherwise, the result is false . If x evaluates to true , y isn't evaluated.

In the following example, the right-hand operand of the || operator is a method call, which isn't performed if the left-hand operand evaluates to true :

The logical OR operator | also computes the logical OR of its operands, but always evaluates both operands.

Nullable Boolean logical operators

For bool? operands, the & (logical AND) and | (logical OR) operators support the three-valued logic as follows:

The & operator produces true only if both its operands evaluate to true . If either x or y evaluates to false , x & y produces false (even if another operand evaluates to null ). Otherwise, the result of x & y is null .

The | operator produces false only if both its operands evaluate to false . If either x or y evaluates to true , x | y produces true (even if another operand evaluates to null ). Otherwise, the result of x | y is null .

The following table presents that semantics:

x y x&y x|y
true true true true
true false false true
true null null true
false true false true
false false false false
false null false null
null true null true
null false false null
null null null null

The behavior of those operators differs from the typical operator behavior with nullable value types. Typically, an operator that is defined for operands of a value type can be also used with operands of the corresponding nullable value type. Such an operator produces null if any of its operands evaluates to null . However, the & and | operators can produce non-null even if one of the operands evaluates to null . For more information about the operator behavior with nullable value types, see the Lifted operators section of the Nullable value types article.

You can also use the ! and ^ operators with bool? operands, as the following example shows:

The conditional logical operators && and || don't support bool? operands.

  • Compound assignment

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

is equivalent to

except that x is only evaluated once.

The & , | , and ^ operators support compound assignment, as the following example shows:

The conditional logical operators && and || don't support compound assignment.

Operator precedence

The following list orders logical operators starting from the highest precedence to the lowest:

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

For the complete list of C# operators ordered by precedence level, see the Operator precedence section of the C# operators article.

Operator overloadability

A user-defined type can overload the ! , & , | , and ^ operators. When a binary operator is overloaded, the corresponding compound assignment operator is also implicitly overloaded. A user-defined type can't explicitly overload a compound assignment operator.

A user-defined type can't overload the conditional logical operators && and || . However, if a user-defined type overloads the true and false operators and the & or | operator in a certain way, the && or || operation, respectively, can be evaluated for the operands of that type. For more information, see the User-defined conditional logical operators section of the C# language specification .

C# language specification

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

  • Logical negation operator
  • Logical operators
  • Conditional logical operators
  • C# operators and expressions
  • Bitwise and shift operators

Additional resources

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

Assignment of variable of type object makes a copy, not by reference?

So I thought I understood how value and type variables work in C# but I encountered a case that's not clear or intuitive to me. If I have a class instance of type "Assembly" (System.Reflection.Assembly) and assign it to another variable, then it seems to be "Copied" rather than by reference:

I obviously get a different assembly (whatever LoadOtherAssembly() gives me) on the second line (assembly1), but "assembly2" seems to have the original Assembly inside.

Whenever I do this with any other class this doesn't happen (as expected):

In this case both spit out "Culley", as expected. What am I missing, and how is this different to the first case, using "Assembly"?

Ayfel's user avatar

  • "but "otherAssembly" seems to have the original Assembly inside." of course it does - you have not changed what otherAssembly references. Are you expecting otherAssembly to always point to the same instance that originalAssembly does, even if you change which object originalAssembly references? –  D Stanley Commented yesterday
  • 1 When you called LoadOtherAssembly(); you created another object, different from the first one. Not the case with your Person example; both variables point to the same object. –  Robert Harvey Commented yesterday
  • 1 You did not do the same with the other class. Look closely at the order of assignments. There is no magic here. –  freakish Commented yesterday

Yo got wrong idea how it works. And your example does not depend whether the variable holds reference or value type.

Now you can similairly think of your example:

To observe "mutability" of reference types, let me present you other, more representative example:

Michał Turczyn's user avatar

  • 2 Yes, thank you for explicitly writing it out with comments. The confusion for me always comes from the "=" and me naively thinking means "same", but as you wrote it really means hold reference r#1 to object o#1, etc. –  Ayfel Commented yesterday
  • @Ayfel If the answer helped you, you should accept it –  Michał Turczyn Commented yesterday

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

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

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Removing undermount sink
  • How to interpret odds ratio for variables that range from 0 to 1
  • Can noun phrases have only one word?
  • In Python 3.12, why does 'Öl' take less memory than 'Ö'?
  • Confused about the uniform distribution of p-values under the null hypothesis
  • Why did mire/bog skis fall out of use?
  • string quartet + chamber orchestra + symphonic orchestra. Why?
  • What's the origin and first meanings of the term "grand piano"?
  • Is this legal to help a friend in need
  • Why did early pulps make use of “house names” where multiple authors wrote under the same pseudonym?
  • Horror short film about a guy trying to test a VR game with spiders in a house. He wakes up and realizes the game hasn't started
  • Invariance of the Lebesgue measure
  • Fear of getting injured in Judo
  • What can I do to limit damage to a ceiling below bathroom after faucet leak?
  • Wondering about ancient methods of estimating the relative planetary distances
  • Can this phrase "the Conservatives opposite" be regarded as apposition structure?
  • Cheapest / Most efficient way for a human Wizard to not age?
  • When did St Peter receive the Keys of Heaven?
  • Why are no metals green or blue?
  • My one-liner 'delete old files' command finds the right files but will not delete them
  • How to plausibly delay the creation of the telescope
  • My math professor is Chinese. Is it okay for me to speak Chinese to her in office hours?
  • Hungarian Immigration wrote a code on my passport
  • Why a relay frequently clicks when a battery is low?

c# result of assignment

IMAGES

  1. How to Control the Result of a Task in C#

    c# result of assignment

  2. C# : ContinueWith and Result of the task

    c# result of assignment

  3. C# Assignment Operator

    c# result of assignment

  4. Assignment Operators in C++

    c# result of assignment

  5. How to Control the Result of a Task in C#

    c# result of assignment

  6. C# Assignment Operator

    c# result of assignment

VIDEO

  1. Aiou Result Autumn 2023 Lates Updates||Aiou Today Updates About Result Assignment Exams||Aiou

  2. ASSIGNMENT 4: C# Scripting

  3. C PROGRAMMING

  4. C Assignment multiplication operator #short #c#assignment #multiplication #operator #printf #coding

  5. MCM304 Assignment Ctrl +C Problem solve new technology

  6. 2- Course C# Resala

COMMENTS

  1. c#

    The assignment will be evaluated first, and the result will then be compared to NULL, i.e. the statement is equivalent to: s = "Hello"; //s now contains the value "Hello" (s != null) //returns true. As others have pointed out, the result of an assignment is the assigned value. I find it hard to imagine the advantage to having ((s = "Hello ...

  2. Assignment operators

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

  3. c#

    the value of an assignment operator is the left operand, so I can see it. That is correct in this case but subtly wrong in general; the value of an assignment operator in C# is the value of the right operand after being converted to the type associated with the left hand side. Remember, the left hand side might not have a value; it could be a ...

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

  5. C#

    Assignment Operators. Conditional Operator. In C#, Operators can also categorized based upon Number of Operands : Unary Operator: Operator that takes one operand to perform the operation. Binary Operator: Operator that takes two operands to perform the operation. Ternary Operator: Operator that takes three operands to perform the operation.

  6. C# Assignment Operators

    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: The addition assignment operator (+=) adds a value to a variable: A list of all assignment operators:

  7. How to Return a Value from Task in C#

    The .NET Framework also provides a generic version of the Task class i.e. Task<T>. Using this Task<T> class we can return data or values from a task. In Task<T>, T represents the data type that you want to return as a result of the task. With Task<T>, we have the representation of an asynchronous method that is going to return something in the ...

  8. ?: operator

    See also. 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: C#. Copy. Run.

  9. ?? and ??= operators

    The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

  10. c#

    If the assignment fails then dog is null, which prevents the contents of the for loop from running, because it is immediately broken out of. If the assignment succeeds then the for loop runs through the iteration. At the end of the iteration, the dog variable is assigned a value of null, which breaks out of the for loop.

  11. C# operator

    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. 00110 ^ 00011 = 00101 The result is 00101 or decimal 5. Console.WriteLine(6 ^ 3); // prints 5 Console.WriteLine(3 ^ 6); // prints 5 C# compound assignment operators. The compound assignment operators consist of two operators.

  12. Null-Coalescing Assignment Operator in C# 8.0

    C# 8.0 has introduced a new operator that is known as a Null-coalescing assignment operator ... Set operators are those operators in query expression which return a result set based on the existence or non-existence of the equivalent elements within the same or different collections or sequences or sets. The standard query operator contains the ...

  13. Operators and expressions

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

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

  15. C#.NET Tutorials For Beginners

    In this C#.NET Tutorials article series, we are going to cover all the basic and advanced concepts of C#. ... How to Control the Result of a Task in C#. 12 of 18 FREE Task-Based Asynchronous Programming in C#. ... Null-Coalescing Assignment Operator in C#. 13 of 14 FREE Unmanaged Constructed Types in C#. 14 of 14 FREE Stackalloc in in C#. Most ...

  16. c#

    If you're interested in having a "switch" expression, you can find the little fluent class that I wrote here in order to have code like this: a = Switch.On(b) .Case(c).Then(d) .Case(e).Then(f) .Default(g); You could go one step further and generalize this even more with function parameters to the Then methods.

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

  18. Addition operators

    In this article. The + and += operators are supported by the built-in integral and floating-point numeric types, the string type, and delegate types.. For information about the arithmetic + operator, see the Unary plus and minus operators and Addition operator + sections of the Arithmetic operators article.. String concatenation. When one or both operands are of type string, the + operator ...

  19. Boolean logical operators

    The result of x & y is true if both x and y evaluate to true. Otherwise, the result is false. ... Compound assignment; See also. C# operators and expressions; Bitwise and shift operators; Collaborate with us on GitHub. The source for this content can be found on GitHub, where you can also create and review issues and pull requests. ...

  20. c#

    So I thought I understood how value and type variables work in C# but I encountered a case that's not clear or intuitive to me. If I have a class instance of type "Assembly" (System.Reflection.Assembly) and assign it to another variable, then it seems to be "Copied" rather than by reference: