C# Tuples as Syntactic Sugar for Multiple Variable Assignment

Published 12 Jun 2020

  • Patterns and Practices

I came across an interesting pattern for using Tuples in an article by Mads Torgersen on C# 9.0 . At first I thought it must be something new in 9.0, but a little digging and actually engaging my brain made me realise it has been possible since C# 7.0 and the introduction of Tuples. It isn't something I've seen anybody else use so I thought it would be worth writing about. 

I have to admit that I've not really looked at Tuples that much and learning a bit more about them reveals some features that allow a style of assignment through destructuring that is ubiquitous in modern JavaScript.

Here is the bit of code from Mads' article that triggered my curiosity (expression bodies wrapped by me for legibility online):

At this point in his article he is actually explaining records using the data keyword (very cool). These feature new init-only properties and are intended as value-like immutable data. He offers the above example as a positional approach to record creation and usage. I have to admit I'd not known about the Deconstruct method which assigns values to any number of out variables. We'll get to that below, but the bit that initially caught my eye was the constructor. Both properties are wrapped in parentheses, as are the two constructor parameters, so the assignments are both done in one line. So what's going on here?

The answer, as I've alluded to above, is Tuple deconstruction. The normal way that you consume tuples as return types is to create the variables in the expression:

The bit that I was not aware of is tucked away at the end of the section on deconstruction in the tuple docs , where it says that you can deconstruct tuples with existing declarations as well, which is what Mads has done. So the code creates a tuple of the existing declared variables, and one from the arguments and assigns values from one to the other.

As a side note, it is worth pointing out that you cannot mix existing declarations with declarations inside the parentheses, it is one or the other.

Why is this a useful pattern to consider? The answer is brevity and readability. Let's look at an example with a simple class and constructor. The standard approach would look like this:

with the destructuring syntax this becomes:

and now we have a shorter single line expression we can also use that other bit of syntactic sugar, the expression body, so we can get the whole constructor on one line:

Many of the improvements that have been applied to C# over the years have been about the reduction in the amount of boilerplate code you need to write, what Jon Skeet refers to as "ceremony". It is about getting the compiler to do the work for you so you can get on with the task at hand. Now you always have to be wary of when terseness turns into obscurity. However, in this case I would argue that this approach is actually more easy to read and comprehend than the traditional approach - it is quite expressive of the intent which is why I like it as a pattern.

JavaScript Style Destructuring

I promised to get back to the Deconstruct method, as this can bring a similar reduction in ceremony, that makes some code that looks very JavaScript-like. As a reminder, Mads' example featured this line:

The power of this method is that it can be used to assign variables like this:

This is why I say it is a strong parallel to JavaScript object destructuring where you would see something like this:

Where this gets really interesting is that you can apply a Deconstruct method to types you have not created via extension methods, so you can use this brief destructuring syntax wherever you want like this:

You can create multiple Deconstruct methods with different out parameters, but this could get confusing and create more work than it saves. As an alternative you can have single/fewer methods and use Discards , another C# 7.0 feature that I've not used. This uses the underscore to assign a temporary dummy variable that is never used by your application. You use it like this:

 I've never really spent much time exploring tuples because I've preferred to instantiate return values as types. I've not found situations where those types felt like an overhead. I'm not sure I've changed my stance on that after spending a bit more time investigating them, but this ability to add a Deconstruct extension to a class to enable destructuring assignment is interesting and I'm going to be looking out for opportunities to use this approach to see how it works.

multiple assignment c#

25 January 2006

10410 views

Printer friendly version

Performance and Multiple Assigment in C#

I was recently thinking if I really liked to use the Multiple assignment in ‘C#’ or if it was less readable. In ‘C’ this syntax was popular as it tended to lead to smaller and quicker code. So I wondered in C# if the multiple assigment also lead to quicker code. So I quickly wrote some test cases to see which style of code was quicker to execute…

I took a rather simplistic model to profile, in order to make the tests more repeatable and easy to follow.

The .NET code followed the followed the structure:

Results are in seconds I did test out directly setting the values eg Count1=100; Count2=100; etc as well as using strings. These variations appeared to give similar results. I carried out the same expermiment under .NET 2 and the results were similar just slightly slower in debug mode. The machine that carried out the tests was an Intel 3.4Ghz P4 running XP SP2 with 1GB RAM.

I guess as ever this proves that it is more important to write readable code that requires the minimum of maintanance, rather than trying to outwit the compiler/CLR. So would I use the multiple assignment? Probably not as much as I used to, but when it leads to easier to read code then yes.

Subscribe for more articles

Fortnightly newsletters help sharpen your skills and keep you ahead, with articles, ebooks and opinion to keep you informed.

Rate this article

multiple assignment c#

David Connell

David Connell is a Software Developer who led the team that created the SQL Data Generator at Red-Gate. Before then, he led the 'SQL Toolbelt' installer and the SQL Doc team, and before that worked in the SQL Bundle 5.0 team. He was previously a Senior Software engineer at Pi Research. In his spare time David Connell develops other software packages with a Dutch Company, Thermimport Quality Control.

Follow David Connell via

View all articles by David Connell

Load comments

Related articles

multiple assignment c#

Azure OpenAI and RAG Security

Code Maze

  • Blazor WASM 🔥
  • ASP.NET Core Series
  • GraphQL ASP.NET Core
  • ASP.NET Core MVC Series
  • Testing ASP.NET Core Applications
  • EF Core Series
  • HttpClient with ASP.NET Core
  • Azure with ASP.NET Core
  • ASP.NET Core Identity Series
  • IdentityServer4, OAuth, OIDC Series
  • Angular with ASP.NET Core Identity
  • Blazor WebAssembly
  • .NET Collections
  • SOLID Principles in C#
  • ASP.NET Core Web API Best Practices
  • Top REST API Best Practices
  • Angular Development Best Practices
  • 10 Things You Should Avoid in Your ASP.NET Core Controllers
  • C# Back to Basics
  • C# Intermediate
  • Design Patterns in C#
  • Sorting Algorithms in C#
  • Docker Series
  • Angular Series
  • Angular Material Series
  • HTTP Series
  • .NET/C# Author
  • .NET/C# Editor
  • Our Editors
  • Leave Us a Review
  • Code Maze Reviews

Select Page

How to Execute Multiple Tasks Asynchronously in C#

Posted by Code Maze | Updated Date Aug 17, 2022 | 4

How to Execute Multiple Tasks Asynchronously in C#

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we are going to learn how to execute multiple tasks in C# in sequence and parallel. By using async/await , we avoid performance bottlenecks and enhance the scalability of our application. Depending on the business logic, we may need to execute functional tasks either sequentially, or in parallel.

Let’s dive into it.

Creating a Demo REST API

Let’s consider that we are developing an application for employee management in an organization. The client/UI application consumes a REST-based API that will return the employee details, salary, and appraisal rating for an employee from three different endpoints.

Become a patron at Patreon!

Here, we will use a simple ASP.NET Core Web API. The controller actions in this Web API return static data for this demo:

Now, let’s take a look at the three endpoints with their response in the swagger documentation for this Web API:

We have made the Web API simple on purpose as we don’t want to deviate from the topic of this article by diving into the intricate implementation details of an ASP.NET Core Web API.

Execute Multiple Tasks in Sequence using async and await

The client application has an EmployeeProfile class which we use as a presentation model to the end-user:

Here, we override the ToString() method to append all the employee data to a single string for printing it to the console.

Since this class acts like a view model, the properties of this class are constructed from the contract classes:

The Executor class in the client application consolidates employee data from all three REST API endpoints while constructing the EmployeeProfile instance:

Here, we are executing the tasks for fetching employee details, salary, and rating in sequence using asynchronous programming .

First, we are awaiting the Task instance returned by the GetEmployeeDetails() method. Then, we do the same with  GetEmployeeSalary() in the continuation of the GetEmployeeDetails() method. Finally, we repeat the action with the GetEmployeeRating() method in the continuation of the GetEmployeeSalary() method. Hence, in this case, each task execution step waits for the previous step to finish without blocking the thread.

In these three methods ( GetEmployeeDetails() , GetEmployeeSalary() , GetEmployeeRating() ) all we do is send a simple HTTP request and process the response . Also, we are simulating a network latency in all three methods using the Task.Delay() method. Such delay is very common in enterprise-grade applications due to factors like slow database calls, geographic factors, etc.

You can find the implementation inside the EmployeeApiFacade class in the client project.

Typically, we do such sequential execution in a workflow where each task execution step is dependent on the previous one, unlike the above steps. However, here we are anyway doing it to demonstrate in a later section the performance improvement that we can achieve by executing these tasks in parallel.

Let’s now run the client application:

We get back the consolidated result. Let’s now see if we can improve the performance of this functionality.

Execute Multiple Tasks in Parallel using Task.WhenAll

Since the tasks for fetching employee details, salary and rating are independent of each other, it is easy to execute them in parallel to improve the overall performance of the workflow:

Here, we are not awaiting the Task instances from any of the methods which means that these methods will now return the Task instances instead of the result and will execute in parallel. However, we need to wait for all three methods to complete their execution before the consolidation of the result. This is achieved by using the WhenAll method from Task Parallel Library.

The Task.WhenAll method creates a Task that will be complete when all the supplied tasks have been completed. Once all three Tasks are complete, we await the individual Task instances to derive the result from them.

Alternatively, we can use the Result property from the Task instances instead of awaiting them to avoid some unnecessary state of machine-generated code during compilation:

Though using blocking code like .Result is not considered good practice under normal circumstances, in this case, it is perfectly safe to use it as all the tasks have finished execution by the time this line is executed. In fact, in this case, it is more beneficial to use this approach as it reduces the size of the compiled code.

Now, when we execute the client code, we get back the consolidated result but with an increase in the overall performance.

Improving the Exception Handling in Task.WhenAll

Handling exceptions play a major part in real-life application development. There is a problem in the above implementation in regards to handling exceptions. Let’s consider a scenario where both GetEmployeeDetails() and GetEmployeeSalary() methods throw exceptions:

In this case, we are only getting the first exception in the console and ignoring the other exception.

So, if other Task instances throw any exceptions, we will never know about it. If we want to get hold of all the exceptions for logging purposes, we need to handle Task.WhenAll a bit differently:

This method extends the Task.WhenAll method to return a ValueTuple with the results of the tasks. Most importantly, it also handles the issue with multiple exceptions by catching and rethrowing an aggregate exception on all tasks that are awaited.

Now, we can invoke the WhenAll method from the TaskExtensions class instead of the original Task.WhenAll in the calling method:

If we execute the client code now, we can see an aggregate exception in the console showing both exceptions:

Performance Comparison async/await vs. Task.WhenAll 

To compare the performance between the two approaches, we have run a benchmark with the default target count:

The ExecuteInParallel() method that uses Task.WhenAll clearly exhibits better overall performance compared to the ExecuteInSequence() method.

Sequential Task Execution using async, await, and foreach Loop

Let’s consider another business workflow where we need to invoke the same REST API endpoint multiple times. For example, invoking the /details/{id} endpoint to fetch details for three different employees. Once again, depending on the business case, we may have to do this either sequentially or in parallel.

To execute the tasks sequentially, we can use a foreach loop:

Here, for each employee id, we call the GetEmployeeDetails() method that invokes the /details/{id} endpoint in the REST API. We await the Task instance returned from the GetEmployeeDetails() method and then write the employee details to the console:

We see that all the tasks are executed. However, these tasks of fetching employee details for multiple employees can very easily be executed in parallel as they are independent of each other. So, executing them in parallel will improve the performance. Let’s see how we can achieve such improvement.

Parallel Tasks Execution using Parallel.Foreach

The Parallel.ForEach method executes a foreach operation in which the iterations may run in parallel.

Let’s re-write the example from the previous section using Parallel.ForEach :

We set the MaxDegreeOfParallelism property to 3. This property limits the number of concurrent operations by the Parallel.ForEach loop to the set value. By default, ForEach will utilize as many threads as the underlying scheduler provides. But, we are limiting this for better utilization of CPU resources in this demo as we have only 3 independent tasks.

Parallel.ForEach does not support asynchronous delegates. So, we are blocking the thread that executes the GetEmployeeDetails() method till it produces a result.

In many cases, Parallel.ForEach can provide significant performance improvements over ordinary sequential loops. However, the work of parallelizing the loop introduces complexity that can lead to problems that we don’t encounter in sequential code. In certain cases, a parallel loop might run slower than its sequential equivalent.

It is better to keep in mind the below points before using the Parallel loops:

  • Parallel loops are designed for CPU-intensive operations. It’s not always the best solution for I/O-bound operations
  • Parallel loops are not appropriate for asynchronous code flow
  • The degree of parallelism is completely dependent on the number of cores and CPU specifications so performance can vary

In the previous code block, each thread runs the independent I/O operations because of the lack of async support in the Parallel.ForEach . This is a big issue considering scalability and has the potential for thread pool starvation in an ASP.NET web application.

However, starting from .NET 6 we can use the Parallel.ForEachAsync method which is async aware.

Parallel Tasks Execution using Parallel.ForeachAsync

The Parallel.ForEachAsync executes a foreach operation on an IEnumerable<T> in which iterations may run in parallel. However, unlike the Parallel.ForEach , it returns a Task instance that represents the entire for-each operation. It also supports an async delegate. This was introduced recently as part of .NET 6.0

Now, let’s re-write the example from the previous section using Parallel.ForEachAsync :

Here, we set the MaxDegreeOfParallelism property to 3 like in the previous section for better optimization of CPU resources.

Now, on executing the client code, we see that the tasks are executed and  it  is approximately similar to the timing that we got using the Parallel.ForEach . 

Performance Comparison foreach vs. Parallel.ForEach vs. Parallel.ForEachAsync

Here also, we have run a benchmark with the default target count:

So, the Parallel.ForEach and the Parallel.ForEachAsync approaches perform better than the normal foreach . We see that there is not much difference in terms of execution time between the Parallel.ForEach and the Parallel.ForEachAsync . However, the scalability of Parallel.ForEachAsync is much higher considering that it is not blocking the individual threads anymore during the I/O operations. Hence, it minimizes the chances of thread pool starvation.

In this article, we have demonstrated a few scenarios where we may need to execute tasks in sequence and parallel. C# provides us with many approaches to achieve the same and we have covered most of them here. One must keep in mind the general pitfalls of asynchronous programming in C# while implementing such task execution.

guest

Hello, so far I use Task.WhenAll to execute multiple tasks like in the example you have given, but I want to use Parallel.ForeachAsync.

I have seen MaxDegreeOfParallelism you have set it to 3. is that because _employeeIds contains 3? If I had 20, would I have to put 20?

The default MaxDegreeOfParallelism for the Parallel.ForEachAsync is equal to the Environment.ProcessorCount, and for all other Parallel methods(For and ForEach) it is equal to -1, which means unlimited parallelism.

The optimal value for the MaxDegreeOfParallelism for CPU-bound operations is Environment.ProcessorCount, although oversubscription might help if the workload is unbalanced.

The Parallel.ForEachAsync is used typically for I/O-bound asynchronous operations, where the sweet spot depends on the capabilities of the remote server or the bandwidth of the network. So in this case there is no rule of thumb, you will have to start with a number and fine-tune it depending on performance.

In this example, we have set the value to 3 simply as we wanted to make at max 3 parallel calls. So you can set it to 20 if your remote service and network can support such concurrent requests. But please also remember, when the CPU has to switch from one thread to another (context switch) it has a cost, so if you use too many threads and the CPU is switching all the time, you decrease the performance.

I am using it in a .NET MAUI application, where I always get a list of 20 elements, I am making a call to the google API. Thanks for the explanation. I don’t know what the correct value would be…

Thank you for the extensive post and benchmarking. While I would write some of the code differently, I appreciate your work and different opinions! Justing starting out as a blogger, I recently posted an in-depth article on best practices in async-await in C#. Maybe you might want to have a go. Cheers,

wpdiscuz

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices .

Using Tuples in C# to Initialize Properties in the Constructor and to Deconstruct Your Object

Recently I was asked by a developer what this code block here actually is:

This is actually a constructor that uses an expression body and tuples.

Since C# 7.0 you can use tuples in your code and you can also use expression bodied constructors. These two features allow you to write constructors in a more compact syntax that you see above. You see this syntax also quite often in code samples and also in the official .NET documentation.

Let’s look at it a bit more detailed. The traditional way to create a constructor and to initialize properties in a constructor looks like below:

Since C# 7.0, you can use tuples in the constructor. The constructor below does this. It creates a tuple with the values of the three constructor parameters and assigns it to a tuple with the three properties. That means this constructor below does exactly the same as the constructor that you see in the code snippet above: It assigns the three parameter values to the three properties FirstName , MiddleName and LastName :

Whenever you have a method, a property accessor, or a constructor with a single statement as the one above, it is a perfect fit to use an expression body. So, you can write the constructor like below, which is the syntax that you have seen at the beginning of this blog post:

Add a Deconstruct Method to Your Class

In the code snippet below I added a Deconstruct method to the Friend class. As you can see, it returns void and it has the three out parameters firstName , middleName , and lastName . In the method body it assigns the values of the properties FirstName , MiddleName , and LastName to the three out parameters.

With that Deconstruct method, you can deconstruct a Friend object into a tuple as shown in the code snippet below.

Now, when you look in the code snippet below at the body of the Deconstruct method, you can see that it has three statements to set all the three out parameters. That’s a perfect use case for tuples.

The code snippet below shows how to use tuples in the Deconstruct method. A tuple for the properties FirstName , MiddleName , and LastName is created and assigned to a tuple with the out parameters firstName , middleName , and lastName .

Now, with that single statement in the Deconstruct method, you can also use an expression body like in the code snippet below.

This leads to a more compact Friend class that looks like below.

As you’ve seen in this blog post, tuples are quite powerful to combine multiple assign statements into a single statement. And by combining tuples with expression bodies you get quite compact code that is still very readable for those who are familiar with tuples.

Happy coding, Thomas

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Share this post

' src=

Thomas Claudius Huber

Comments (6)

' src=

In ihrem WPF buch, 5te Auflage, Seite 489, bei ICommand ist in dem Code Beispiel Leerzeichen Setzung der Properties kaputt.

Danke, eben nachgeschaut, stimmt. Hat beim Setzen wohl jemand die Leerzeichen aufgegessen. :) Ist allerdings immer noch gültiger C# Code, aber ja, unschön formatiert. Danke für den Hinweis.

' src=

Hello Thomas

public Friend(string firstName, string middleName, string lastName) { (FirstName, MiddleName, LastName) = (firstName, middleName, lastName); }

turns into casual assignment

public Friend(string firstName, string middleName, string lastName) { string text2 = (FirstName = firstName); text2 = (MiddleName = middleName); text2 = (LastName = lastName); }

on sharplab : https://tinyurl.com/assignmentTuple

' src=

This was super clear and informative! It’s not so often you read a technical article that is as well written as this one. Learned and enjoyed reading this, I appreciate your effort and hope you continue to create material for a long time!

Thank you Snoopy, glad you enjoyed it!

' src=

Thanks, C# 7+ Tuples makes more sense now :)

Leave a Reply Cancel reply

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

Spam protection: Sum of 3 + 9 ? *

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Related Posts

C# 12: default parameters in lambda expressions.

In the previous blog posts of this C# 12 series you learned about different C# 12 features: Primary Constructors Collection Expressions Alias Any... read more

C# 12: Alias Any Type

In the previous blog posts of this C# 12 series you learned about different C# 12 features: Primary Constructors Collection Expressions In this... read more

C# 12: Collection Expressions

In the previous blog post you learned about C# 12 primary constructors. In this blog post, you will learn about... read more

C# 12: Primary Constructors

In November 2023, Microsoft released .NET 8.0, and since then you can use C# 12.So, it might be a good... read more

Create a GitHub Action in Visual Studio to Deploy Your .NET Web App automatically to Azure on Every Commit

When building a web application, it can be helpful to deploy your application with the latest features and code changes... read more

C# 11.0: Generic Math, C# Operators and Static Abstract/Virtual Interface Members

In the previous blog posts you learned about different C# 11.0 features: Raw String Literals Generic Attributes In this blog post, let's look... read more

C# 11.0: Generic Attributes

In the previous blog post you learned about C# 11.0 raw string literals. In this blog post, you will learn about another... read more

C# 11.0: Raw String Literals

In November 2022, .NET 7.0 was released, and since then, you can use C# 11.0. In version 11.0, the C# language... read more

C# 10.0: Extended Property Patterns – Use the Dot Token to Access Nested Members

In the previous blog posts you learned about different C# 10.0 features: File-scoped namespaces Global using directives In this blog post, let's look... read more

C# 10.0: Global Using Directives – Make Important Namespaces Available in Your Whole Project

In the previous blog post you learned about C# 10.0 file-scoped namespaces. In this blog post you learn about another C# 10.0... read more

C# Tutorial

C# examples, c# multiple variables, declare many variables.

To declare more than one variable of the same type , use a comma-separated list:

Try it Yourself »

You can also assign the same value to multiple variables in one line:

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.

DEV Community

DEV Community

Matheus Gomes 👨‍💻

Posted on Jan 5, 2020

Coalescing operator and Compound assignment operator in C#

Hello! Today i want to ask you this: Have you ever used a Null Coalescing operator or even a Compound assignment operator in C# ?

Until today i had never heard about this things, so i want to share with you what i learned about and how it can be applied to your code.

The problem

Let's say you want to give a given variable the value of null.

Now, if we want to print the value on the screen it will accuse the following error:

Let's see how to get around this...

The old way 👎

The old and 'commom way' to check this is using if else operators like this:

We see that in this case we cannot place a default value to x and y operators. So we display on screen when it is null.

The Null Coalescing operator way 👌

First, a null coalescing operator (??) is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null, otherwise, it returns the right operand.

So it's mainly used to simplify checking for null values and also assign a default value to a variable when the value is null.

Using our example:

This way i can make a default value on x and y when one of them is null. And so, we can print on screen!

But can it be better?

The Compound assignment operator way 😎

The Compound assignment operator (??=) was introduced on C# 8.0 and has made our job easier. It simply reduces what we have to write and has the same result.

Instead of writing double x = x ?? 0.0; We can just write double x ??= 0.0;

Simple, right?

Hope you enjoyed this post, it's simple but it's something worth sharing for me.

Thanks for your time!😊

Links: https://dzone.com/articles/nullable-types-and-null-coalescing-operator-in-c

https://dev.to/mpetrinidev/the-null-coalescing-operator-in-c-8-0-4ib4

https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/operators/null-coalescing-operator

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

wakeupmh profile image

  • Email [email protected]
  • Location São José dos Campos
  • Work Cloud Engineer | AWS Community Builder
  • Joined May 21, 2019

saint4eva profile image

  • Joined Dec 16, 2017

Good article. Thank you.

arthurbarbero profile image

  • Location Brazil
  • Work Intern at Agrotools
  • Joined Oct 22, 2019

Awesome Dude, simple but unknown by most programmers

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

ssukhpinder profile image

Day 15 of 30-Day .NET Challenge: Lazy Initialization

Sukhpinder Singh - Apr 3

homolibere profile image

The Dangling If-Else Problem: A Common Pitfall in Programming

Nick - Mar 15

bearevans profile image

How-To: Event Systems in Unity

Bear Evans - Apr 8

derlin profile image

Exploring The Magic of Python Through The Awesome Slumber Library

Lucy Linder - Apr 8

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

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

multiple assignment c#

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

multiple assignment 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 *

This browser is no longer supported.

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

?: operator - the ternary conditional operator

  • 11 contributors

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

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

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

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

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

is evaluated as

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

Conditional ref expression

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

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

The syntax for a conditional ref expression is as follows:

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

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

Conditional operator and an if statement

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

Operator overloadability

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

C# language specification

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

Specifications for newer features are:

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

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

Tutlane Logo

C# Variables with Examples

In c#, Variables will represent storage locations, and each variable has a particular type that determines what type of values can be stored in the variable.

C# is a Strongly Typed programming language. Before we perform any operation on variables, it’s mandatory to define a variable with the required data type to indicate what type of data that variable can hold in our application.

Syntax of C# Variables Declaration

Following is the syntax of declaring and initializing variables in the c# programming language.

If you observe the above syntax, we added a required data type before the variable name to tell the compiler about what type of data the variable can hold or which data type the variable belongs to.

  • [Data Type] - It’s a type of data the variable can hold, such as integer, string, decimal, etc. 
  • [Variable Name] - It’s the name of the variable to hold the values in our application. 
  • [Value] - Assigning a required value to the variable. 
  • [Access Specifier] - It is used to define access permissions for the variable.

Now we will see how to define variables in our c# applications with examples.

  • C# Variables Declaration Example

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

If you observe the above c# variables example, we defined multiple variables with different data types and assigned values based on our requirements.

Output of C# Variables Declaration Example

When you execute the above program by pressing Ctrl + F5 or clicking on the  Start option in the menu bar, you will get the result shown below.

C# Variables Declaration Example Result

If you observe the above result, we are able to print the variables in our c# application based on our requirements.

Rules to Declare C# Variables

Before we declare and define variables in the c# programming language, we need to follow particular rules.

  • You can define a variable name with a combination of alphabets, numbers, and underscore.
  • A variable name must always start with either alphabet or underscore but not with numbers.
  • While defining the variable, no white space is allowed within the variable name.
  • Don't use any reserved keywords such as int, float, char, etc., for a variable name.
  • In c#, once the variable is declared with a particular data type , it cannot be re-declared with a new type, and we shouldn’t assign a value that is not compatible with the declared type.

The following are some  valid ways to define the variable names in the c# programming language.

The following are some of the  Invalid ways of defining the variable names in the c# programming language.

C# Multiple and Multi-Line Variables Declaration

In c#, we can declare and initialize multiple variables of the same data type in a single line by separating with a comma.

Following is the example of defining the multiple variables of the same data type in a single line by separating with a comma in the c# programming language.

While declaring the multiple variables of the same data type, we can arrange them in multiple lines to make them more readable. The compiler will treat it as a single statement until it encounters a semicolon ( ; ).

Following is the simple of defining the multiple variables of the same data type in multiple lines in c# programming language.

C# Variables Assignment

In c#, once we declare and assign a value to the variable that can be assigned to another variable of the same data type.

Following is the example of assigning a value of one variable to another variable of the same type in c# programming language.

In c#, it’s mandatory to assign a value to the variable before we use it; otherwise, we will get a compile-time error.

If we try to assign a value of string data type to an  integer data type or vice versa, as shown below, we will get an error like “ cannot implicitly convert type int to string ”.

This is how we can use variables in the c# programming language based on our requirements. 

Table of Contents

  • Variables in C# with Examples
  • Rules to Declare a Variables in C#
  • C# Multiple and Multi Line Variable Declarations
  • Variable Assignment in C# with Example

IMAGES

  1. How to Execute Multiple Tasks in C# with Examples

    multiple assignment c#

  2. 6.1. Multiple assignment

    multiple assignment c#

  3. C# Assignment Operator

    multiple assignment c#

  4. How to Execute Multiple Tasks in C# with Examples

    multiple assignment c#

  5. 51. Assignment and Multiple Assignment Statement in C Programming (Hindi)

    multiple assignment c#

  6. Multiple assignment in variable

    multiple assignment c#

VIDEO

  1. MULTIPLE assignment and COMBINED assignment (C++ basics)

  2. Assignment 1 PRN221

  3. #20 Assignment Operators in C#

  4. Assignment final C#

  5. VARIABLES & MULTIPLE ASSIGNMENT

  6. Nov 4 End of semester review

COMMENTS

  1. .net

    Those of us whose programming is more mathematical in nature very much appreciate multiple assignment / tuple support in the language. I recently made extensive use of F# because of this, using only C# in places where I had to interact with COM code, because F# let us more or less transliterate the formalisms from our paper straight into code.

  2. c#

    The logic is as follows: The assignment operation itself returns a value, which is the value that has been assigned. The sequence of execution is: num1 = (num2 = 5) and the first assignment which is executed ( num2 = 5) returns the value 5 to the outside world - which is in turn assigned to num1. This works ad infinitum ( num0 = num1 = num2 = 5 ...

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

  4. Deconstructing tuples and other types

    Retrieving multiple field and property values from an object can be equally cumbersome: you must assign a field or property value to a variable on a member-by-member basis. You can retrieve multiple elements from a tuple or retrieve multiple field, property, and computed values from an object in a single deconstruct operation. To deconstruct a ...

  5. C# Tuples as Syntactic Sugar for Multiple Variable Assignment

    You can create multiple Deconstruct methods with different out parameters, but this could get confusing and create more work than it saves. As an alternative you can have single/fewer methods and use Discards, another C# 7.0 feature that I've not used. This uses the underscore to assign a temporary dummy variable that is never used by your ...

  6. Performance and Multiple Assigment in C#

    I was recently thinking if I really liked to use the Multiple assignment in 'C#' or if it was less readable. In 'C' this syntax was popular as it tended to lead to smaller and quicker code. So I wondered in C# if the multiple assigment also lead to quicker code. So I quickly wrote some test cases to see which style of code was quicker ...

  7. How to Execute Multiple Tasks Asynchronously in C#

    Once again, depending on the business case, we may have to do this either sequentially or in parallel. To execute the tasks sequentially, we can use a foreach loop: public async Task<IEnumerable<EmployeeDetails>> ExecuteUsingNormalForEach(IEnumerable<Guid> employeeIds) {. List<EmployeeDetails> employeeDetails = new();

  8. Using Tuples in C# to Initialize Properties in the Constructor and to

    Since C# 7.0, you can use tuples in the constructor. The constructor below does this. ... As you've seen in this blog post, tuples are quite powerful to combine multiple assign statements into a single statement. And by combining tuples with expression bodies you get quite compact code that is still very readable for those who are familiar ...

  9. C# Multiple Variables

    Example Get your own C# Server. int x = 5, y = 6, z = 50; Console.WriteLine(x + y + z); Try it Yourself ». You can also assign the same value to multiple variables in one line:

  10. Object and Collection Initializers

    The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment. Object initializers can set indexers, in addition to assigning fields and properties. Consider this basic Matrix class: C#. Copy.

  11. How to Execute Multiple Tasks in C#

    string message = $"Credit Card Number: {creditCard.CardNumber} Name: {creditCard.Name} Processed"; Console.WriteLine($"Credit Card Number: {creditCard.CardNumber} Processed"); return message; } Next, we are creating another asynchronous method to execute multiple tasks concurrently.

  12. Multiple inline assignments in one statement in c#

    Obviously the following is totally fine in c#; int a; int b = a = 2; Is it possible to do multiple variable assignments in c# in a single statement? i.e. something like; int a = (int b = 2);

  13. Discards

    One typical use is to use an assignment to ensure that an argument isn't null. The following code uses a discard to force an assignment. The right side of the assignment uses the null coalescing operator to throw an System.ArgumentNullException when the argument is null. The code doesn't need the result of the assignment, so it's discarded.

  14. C# Multiple Local Variables

    Let us consider the C# syntax for multiple locals on a single statement. The comma character is used, and the type name is repeated. int x = 1, y = 2; SAME AS: int x = 1; int y = 2; Example code. We introduce a program that uses the multiple local variable declarator syntax. You can declare and optionally assign several variables in a single ...

  15. Coalescing operator and Compound assignment operator in C#

    Hello! Today i want to ask you this: Have you ever used a Null Coalescing operator or even a Compound assignment operator in C# ? I never. Until today i had never heard about this things, so i want to share with you what i learned about and how it can be applied to your code. The problem Let's say you want to give a given variable the value of ...

  16. Operators in C# with Examples

    For example, consider the expression 2 + 3 = 5, here 2 and 3 are operands, and + and = are called operators. So, the Operators in C# are used to manipulate the variables and values in a program. int x = 10, y = 20; int result1 = x + y; //Operator Manipulating Variables, where x and y are variables and + is operator.

  17. c#

    This works because the C# compiler performs the rightmost assignment first; that is, d = 5. That assignment itself returns a value, the value 5. The compiler then assigns that returned value to c. That second assignment also returns a value, and so on, until all the variables have been assigned.

  18. C#'s conditional operator (?:) explained · Kodify

    ApplCount():0); Here we use the Console.WriteLine()method to print the number of appliances we need for an order. We base that count on the isKitchenBoolean variable. When that one is true, the conditional operator executes ApplCount()and returns that method's value. Should that variable be false, the operator returns 0.

  19. ?: operator

    You can ref assign the result of a conditional ref expression, use it as a reference return or pass it as a ref, out, in, or ref readonly method parameter. You can also assign to the result of a conditional ref expression, as the preceding example shows. ... C# language specification. For more information, see the Conditional operator section ...

  20. c

    sample1 = 0; sample2 = 0; specially if you are initializing to a non-zero value. Because, the multiple assignment translates to: sample2 = 0; sample1 = sample2; So instead of 2 initializations you do only one and one copy. The speed up (if any) will be tiny but in embedded case every tiny bit counts!

  21. C# Variables with Examples

    Following is the example of defining the multiple variables of the same data type in a single line by separating with a comma in the c# programming language. int a, b, c; float x, y, z = 10.5; While declaring the multiple variables of the same data type, we can arrange them in multiple lines to make them more readable.