last modified January 15, 2024

In this article we show how to work with a List collection in C#.

C# List initializer

C# lists can be initialized with literal notation. The elements are added on the right side of the assignment inside {} brackets.

A new list is created. Between the angle brackets ( <> ), we specify the data type of the list elements.

To get a quick look at the contents of the list, we join all the values into a string, separated by comma.

C# List collection expression

.NET 8 introduced a terse syntax to create and initialize a list.

C# List count elements

With the Count property, we get the number of elements in the list.

The example counts the number of elements in the list.

C# List access elements

Elements of a list can be accessed using the index notation [] . The index is zero-based.

The example prints the first, second, and the last element of the list.

With the ^ operator, we can access elements from the end of the list.

C# List add elements

The example creates two lists and adds new elements to it.

With AddRange method, we add another collection to the list.

C# List insert elements

The Insert method inserts an element into the list at the specified index. The InsertRange inserts the elements of a collection into the list at the specified index.

C# List Contains

In the example, we check if the oak word is in the list.

C# List removing elements

With RemoveAll method, we remove all elements that satisfy the given predicate; in our case, we remove all negative values.

The RemoveRange method removes the given range of values from the list. The parameters are the zero-based starting index of the range of elements to remove and the number of elements to remove.

C# List ToArray

C# list foreach.

The ForEach method performs the specified action on each element of a list.

C# loop List

The example shows three ways of looping over a list in C#.

We loop over a list with ForEach .

C# sort, reverse List

C# list findall.

The FindAll method retrieves all the elements of a list that match the conditions defined by the specified predicate. It returns a list containing all the elements that match the conditions defined by the specified predicate, if found; otherwise, an empty list.

C# List Find, FindLast, FindIndex, FindLastIndex

The Find method returns the first occurrence of the element that matches the given predicate. The FindLast method returns the last occurrence of the element that matches the given predicate.

C# List ConvertAll

The ConvertAll method converts the elements in the current List to another type, and returns a list containing the converted elements.

In the example, we have a list of words. We convert the list to two other lists.

In the second case, the converted list contains integers that are the length of the words in the original list.

In the second example, we have a separate squareRoot method, which is applied on the list of integers.

In the example, we create a new list by applying square root operation on the list of integers.

C# List shuffle

In the example, we create a Shuffle extension method. It shuffles the elements in-place.

C# List TrueForAll

Not all elements are even and all elements are positive.

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language.

Via LINQ, C# exposes plenty of methods for working with List data.

C# List aggregate calculations

In the program, we use the Count, Sum, Average, Max, and Min methods.

C# List ordering

We have a list of users. The users are sorted first by their last names, then by their salaries.

We sort the users by their last names and then by their salaries in ascending order.

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

List all C# tutorials .

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

assignment list c#

C# - List<T>

The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.Collections.Generic namespace.

List<T> Characteristics

  • List<T> equivalent of the ArrayList , which implements IList<T> .
  • It comes under System.Collections.Generic namespace.
  • List<T> can contain elements of the specified type. It provides compile-time type checking and doesn't perform boxing-unboxing because it is generic.
  • Elements can be added using the Add() , AddRange() methods or collection-initializer syntax.
  • Elements can be accessed by passing an index e.g. myList[0] . Indexes start from zero.
  • List<T> performs faster and less error-prone than the ArrayList .

Creating a List

The List<T> is a generic collection, so you need to specify a type parameter for the type of data it can store. The following example shows how to create list and add elements.

In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In the same way, cities and bigCities are string type list. You can then add elements in a list using the Add() method or the collection-initializer syntax.

You can also add elements of the custom classes using the collection-initializer syntax. The following adds objects of the Student class in the List<Student> .

Adding an Array in a List

Use the AddRange() method to add all the elements from an array or another collection to List.

AddRange() signature: void AddRange(IEnumerable<T> collection)

Accessing a List

A list can be accessed by an index, a for/foreach loop, and using LINQ queries. Indexes of a list start from zero. Pass an index in the square brackets to access individual list items, same as array. Use a foreach or for loop to iterate a List<T> collection.

Accessing a List using LINQ

The List<T> implements the IEnumerable interface. So, we can query a list using LINQ query syntax or method syntax, as shown below.

Insert Elements in List

Use the Insert() method inserts an element into the List<T> collection at the specified index.

Insert() signature: void Insert(int index, T item);

Remove Elements from List

Use the Remove() method to remove the first occurrence of the specified element in the List<T> collection. Use the RemoveAt() method to remove an element from the specified index. If no element at the specified index, then the ArgumentOutOfRangeException will be thrown.

Remove() signature: bool Remove(T item)

RemoveAt() signature: void RemoveAt(int index)

Check Elements in List

Use the Contains() method to determine whether an element is in the List<T> or not.

List<T> Class Hierarchy

The following diagram illustrates the List<T> hierarchy.

List<T> Class Properties and Methods

The following table lists the important properties and methods of List<T> class:

Property Usage
Items Gets or sets the element at the specified index
Count Returns the total number of elements exists in the List<T>
Method Usage
Add Adds an element at the end of a List<T>.
AddRange Adds elements of the specified collection at the end of a List<T>.
BinarySearch Search the element and returns an index of the element.
Clear Removes all the elements from a List<T>.
Contains Checks whether the specified element exists or not in a List<T>.
Find Finds the first element based on the specified predicate function.
Foreach Iterates through a List<T>.
Insert Inserts an element at the specified index in a List<T>.
InsertRange Inserts elements of another collection at the specified index.
Remove Removes the first occurrence of the specified element.
RemoveAt Removes the element at the specified index.
RemoveRange Removes all the elements that match the supplied predicate function.
Sort Sorts all the elements.
TrimExcess Sets the capacity to the actual number of elements.
TrueForAll Determines whether every element in the List<T> matches the conditions defined by the specified predicate.
  • How to sort the generic SortedList in the descending order?
  • Difference between Array and ArrayList
  • Difference between Hashtable and Dictionary
  • How to write file using StreamWriter in C#?
  • Difference between delegates and events in C#
  • How to read file using StreamReader in C#?
  • How to calculate the code execution time in C#?
  • Design Principle vs Design Pattern
  • How to convert string to int in C#?
  • Boxing and Unboxing in C#
  • More C# articles

assignment list c#

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • C# Questions & Answers
  • C# Skill Test
  • C# Latest Articles

Tutlane Logo

C# Assignment Operators with Examples

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

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

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

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

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

C# Assignment Operators Example

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

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

Output of C# Assignment Operators Example

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

C# Assigenment Operator Example Result

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

Table of Contents

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

C# Corner

  • TECHNOLOGIES
  • An Interview Question

C#

C# List Tutorial - Everything You Need To Learn About List In C#

assignment list c#

  • Mahesh Chand
  • Apr 02, 2023
  • Other Artcile

Learn how to use C# List and its methods and properties.

C# List class represents a collection of strongly typed objects that can be accessed by index. This tutorial teaches how to work with lists in C# using the C# List class to add, find, sort, reverse, and search items in a collection of objects using List class methods and properties.

What is C# List?

List<T> class in C# represents a strongly typed list of objects. The C# List provides functionality to create a list of objects, add items to a list, and find, sort, and update items in the List. In this article, learn how to create a list in C#, add items to a list, and find and remove items to a list. 

Create a List in C#

C# List is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the List <T>, class.

List<T> class constructor is used to create a List object of type T. It can either be empty or take an Integer value as an argument that defines the initial size of the List, also known as capacity. If no integer is passed in the constructor, the size of the List is dynamic and grows every time an item is added to the array. You can also give an initial collection of elements when initializing an object. 

The code snippet in Listing 1 creates a List of Int16 and a list of string types. The last part of the code creates a List<T> object with an existing collection.

As you can see from Listing 1, the List <string> has only an initial capacity set to 5. However, when more than five elements are added to the List, it automatically expands. 

Add an item to a C# List

The Add method adds an element to a C# List. For example, the code snippet in Listing 2 creates two List <T> objects and adds integer and string items.

We can also add a collection to a List. The AddRange method is used to add a group to a List. For example, the code snippet in Listing 3 adds an array of strings to a List.

Loop through a C# List items

The C# List is a collection of items. We can use a foreach loop to loop through its items. The code snippet in Listing 6 reads all list items and displays them on the console.

Listing 4. 

We can use the collection's index to retrieve an item in a C# List at a specific position. For example, the following code snippet reads the 3rd item in the List.

C# List properties

List class properties include the following:

  • Capacity – Number of elements List<T> can contain. The default capacity of a List<T> is 0.
  • Count – Number of elements in List <T>.

The code snippet in Listing 5 gets the value of these properties.

Insert an item at a position in a C# List

The Insert method of the List class inserts an object at a given position. The first parameter of the method is the 0th-based index in the List.

The InsertRange method can insert a collection at the given position. 

The code snippet in Listing six inserts a string at the 3rd position and an array at the 2nd position of the List <T>.

Remove an item from a C# List

The List class provides Remove methods that can be used to remove an item or a range of items. 

The Remove method removes the first occurrence of the given item in the List. For example, the following code snippet removes the first occurrence of 'New Author1'.

The RemoveAt method removes an item at the given position. For example, the following code snippet removes the item at the 3rd position.

The RemoveRange method removes a list of items from the starting index to the number of items. For example, the following code snippet removes two items starting at the 3rd position.

The Clear method removes all items from a List<T>. For example, the following code snippet removes all items from a List.

Clear all items from a C# List

The Clear method removes all items from a C# List. For example, the following code snippet removes all items from a List.

Check if an item exists in a C# List

The IndexOf method finds an item in a List. The IndexOf method returns -1 if no items are located in the List. 

The following code snippet finds a string and returns the matched position of the item.

We can also specify the position in a List from which the IndexOf method can start searching. 

For example, the following code snippet finds a string starting at the 3rd position in a String.

The LastIndexOf method finds an item from the end of the List. 

The following code snippet looks for a string in the backward direction and returns the index of the item if found.

The complete example is listed in Listing 7.

Listing 7.  

Sort a C# List

The Sort method of List <T> sorts all items of the List using the QuickSort algorithm. 

The following code example in Listing eight sorts List items and displays both the original and sorted order of the List items.

Listing 8. 

The output of Listing eight looks like Figure 2. 

assignment list c#

Figure 2. 

Reverse a C# List

The Reverse method of List <T> reverses the order of all items in the List. 

The following code snippet reverses a List. 

Listing 9. 

The output of Listing nine looks like Figure 3. 

assignment list c#

Figure 3. 

Find an Item in a C# List

The BinarySearch method of List <T> searches a sorted list and returns the zero-based index of the found item. The List <T> must be sorted before this method can be used. 

The following code snippet returns an index of a string in a List.

Import items to a C# List from another List

You can use the AddRange method of List to import items from one List into another list. But make sure the item types are the same in both lists. For example, the following code snippet creates two List objects and copies all items of listTwo into listOne.

 Convert a C# List to an array

You can use the ToArray() method of the C# List class to convert a list into an array.

Join two C# Lists

You can use the AddRange method to merge a C# List with an existing C# List. Here is a detailed article on How to Merge Two C# Lists . 

Summary 

This article demonstrated how to use a List<T> class to work with a collection of objects. The article also showed how to add, find, search, sort, and reverse items in a List. 

  • C# List Code Examples
  • ListT Class

C# Corner Ebook

Mastering SOLID Principles in C#

assignment list c#

C# Assignment Operators

Introduction.

In C#, assignment operators are used to assign values to variables. They include both simple assignment operators and compound assignment operators. Here's a list of assignment operators in C#:

Simple Assignment Operator ( = ): Assigns the value of the right-hand operand to the left-hand operand.

Addition Assignment Operator ( += ): Adds the value of the right-hand operand to the left-hand operand and assigns the result to the left-hand operand.

Subtraction Assignment Operator ( -= ): Subtracts the value of the right-hand operand from the left-hand operand and assigns the result to the left-hand operand.

Multiplication Assignment Operator ( *= ): Multiplies the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.

Division Assignment Operator ( /= ): Divides the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.

Modulus Assignment Operator ( %= ): Computes the modulus (remainder of division) of the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.

Bitwise AND Assignment Operator ( &= ): Performs a bitwise AND operation between the left-hand operand and the right-hand operand and assigns the result to the left-hand operand.

Bitwise OR Assignment Operator ( |= ): Performs a bitwise OR operation between the left-hand operand and the right-hand operand and assigns the result to the left-hand operand.

Bitwise XOR Assignment Operator ( ^= ): Performs a bitwise XOR operation between the left-hand operand and the right-hand operand and assigns the result to the left-hand operand.

These are the assignment operators in C#. You can use them to perform various operations and assign values to variables in your C# programs.

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# Sharp Exercises
  • Introduction
  • Basic Algorithm
  • Exception Handling
  • Conditional Statements
  • Searching and Sorting
  • Regular Expression
  • File Handling
  • ..More to come..
  • C# Sharp Programming Exercises, Practice, Solution

What is C# Sharp?

C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more.

C# syntax is highly expressive, yet it is also simple and easy to learn. The curly-brace syntax of C# will be instantly recognizable to anyone familiar with C, C++ or Java. Developers who know any of these languages are typically able to begin to work productively in C# within a very short time.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with C# Sharp programming. Hope, these exercises help you to improve your C# Sharp programming coding skills. Currently, following sections are available, we are working hard to add more exercises .... Happy Coding!

Latest Exercises : C# Sharp Exception Handling     

List of C# Sharp Exercises :

  • Basic Exercises [ 104 Exercises with Solution ]
  • Basic Algorithm [ 150 Exercises with Solution ]
  • Exception Handling [13 exercises with solution]
  • Data Types Exercises [ 11 Exercises with Solution ]
  • Conditional Statement Exercises [ 25 Exercises with Solution ]
  • For Loop Exercises [ 83 Exercises with Solution ]
  • Array Exercises [ 41 Exercises with Solution ]
  • Stack Exercises [ 27 Exercises with Solution ]
  • Searching and Sorting Algorithm [ 11 Exercises with Solution ]
  • String Exercises [ 68 Exercises with Solution ]
  • Function Exercises [ 10 Exercises with Solution ]
  • Math Exercises [ 24 Exercises with Solution ]
  • Recursion Exercises [ 15 Exercises with Solution ]
  • Regular Expression Exercises [ 9 Exercises with Solution ]
  • LINQ Exercises [ 30 Exercises with Solution ]
  • STRUCTURE Exercises [ 10 Exercises with Solution ]
  • Date Time Exercises [ 57 Exercises with Solution ]
  • File Handling Exercises [ 15 Exercises with Solution ]
  • More to Come !

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

Note : The solution of the exercises described here are not the only ways to do stuff. Rather, it would be great, if this helps you anyway to choose your own methods.

[ Want to contribute to C# Sharp exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • 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.

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

I am writing my testcode and I do not want wo write:

I would love to write

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

  • collections
  • initialization

John Smith's user avatar

10 Answers 10

Essentially the syntax is:

Which is translated by the compiler as

Matthew Abbott's user avatar

  • 1 I like this no-parentheses method, what c# version did that start with? –  SilverbackNet Commented Dec 14, 2010 at 10:36
  • 10 It's not quite translated into that, at least not in general. The assignment to the variable happens after all the Add calls have been made - it's as if it uses a temporary variable, with list = tmp; at the end. This can be important if you're reassigning a variable's value. –  Jon Skeet Commented Dec 14, 2010 at 10:38
  • Automatic Properties and Object Initialisers were introduced with .NET 3 I believe, it's the same Framework version, just an updated compiler to support LINQ. –  Matthew Abbott Commented Dec 14, 2010 at 10:38
  • @Jon, Cheers, I never knew that part. :D –  Matthew Abbott Commented Dec 14, 2010 at 10:39
  • 1 @Tony Consider: list = new List<string> { list[1], list[2], list[0] }; - you don't want list replaced with an empty List<string> before the elements are added. –  NetMage Commented Apr 1, 2020 at 21:31

Change the code to

Adriaan Stander's user avatar

  • 1 what is the purpose of using the second line " List<string> nameslist = new List<string>(new[] {"one", "two", "three"}); " when can we use it ? Also what is meaning of "new[] {...} " in the second syntax ?why new keyword is used along with the parenthesis [] ??? –  Tony Commented May 24, 2015 at 2:52

Just lose the parenthesis:

Joe the Person's user avatar

  • Oops, look like five people beat me to it. –  Richard Fawcett Commented Dec 14, 2010 at 10:36

Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.

You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.

OR by parameterized constructor

MDT's user avatar

This is one way.

This is another way.

Same goes with strings.

Dima Kozhevin's user avatar

Remove the parentheses:

Tim Robinson's user avatar

It depends which version of C# you're using, from version 3.0 onwards you can use...

Sam Salisbury's user avatar

I think this will work for int, long and string values.

Muhammad Awais's user avatar

C# 12 (.NET 8+) way is:

though don't use var with it, it needs to know the type since the new collection literals can be used for any kind of collection.

Source: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12#collection-expressions

Hossein Ebrahimi's user avatar

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# list collections initialization or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Bringing clarity to status tag usage on meta sites
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Correct anonymization of submission using Latex
  • What is the least number of colours Peter could use to color the 3x3 square?
  • Overstaying knowing I have a new Schengen visa
  • Can we use "day and night time" instead of "day and night"?
  • Big Transition of Binary Counting in perspective of IEEE754 floating point
  • Why does each leg of my 240V outlet measure 125V to ground, but 217V across the hot wires?
  • Is it true that before modern Europe, there were no "nations"?
  • Why public key is taken in private key in Kyber KEM?
  • How resiliant is a private key passphase to brute force attacks?
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • I want to write a script that simultaneously renders whats on my webcam to a window on my screen and records a video
  • Text processing: Filter & re-publish HTML table
  • Did Queen (or Freddie Mercury) really not like Star Wars?
  • Electromagnetic Eigenvalue problem in FEM yielding spurious solutions
  • Is the product of two NONZERO elements independently drawn from a prime field uniformly distributed?
  • If a friend hands me a marijuana edible then dies of a heart attack am I guilty of felony murder?
  • What is the shortest viable hmac for non-critical applications?
  • Unstable plans when two first index columns have NULL values in all rows
  • Does innate sorcery apply to every attack from storm sphere?
  • Canonical decomposition as wedge sum up to homotopy equivalence
  • Where Does Rashi Mention the Streets of Venice?
  • What does "Mas que nada" mean and how does that derive from the individual words?
  • Movie / episode where a spaceplane is stuck in orbit
  • Why wasn't Randall Stevens caught?

assignment list c#

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

IMAGES

  1. C# Assignment Operator

    assignment list c#

  2. Learn C# Programming

    assignment list c#

  3. C# List

    assignment list c#

  4. C# List: Everything You Need to Know

    assignment list c#

  5. C# Operators

    assignment list c#

  6. C# List with examples

    assignment list c#

VIDEO

  1. ASSIGNMENT 4: C# Scripting

  2. Visual Application

  3. Assignment 1 PRN221

  4. Assignment 06

  5. Assignment 01

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

COMMENTS

  1. c#

    The problem is the assignment. Until the assignment name_list2 = name_list1;, you have two different List objects on the heap pointed to by the variables name_list1 and name_list2.You fill up name_list1, which is fine.But the assignment says, "make name_list2 point to the same object on the heap as name_list1."The List that name_list2 used to point to is no longer accessible and will be ...

  2. Assignment operators

    Assignment operators (C# reference)

  3. C# assign value to List<string> at specific index

    The array indexer directly references the element in the array (collection) variable, to which you can assign something. The method call doesn't reference anything, it returns something. So you can assign to a variable: x = "some value"; Even an index of a collection variable: x[0] = "some value"; But not to a method call:

  4. C# List

    C# List - working with a List collection in C#

  5. Work with List\\<T>

    Work with List\ - Introductory tutorial - A tour of C# | ...

  6. C# Assignment Operators

    C# Assignment Operators

  7. C# List<T> Collection

    C# List Collection

  8. C# Assignment Operators with Examples

    C# Assignment Operators with Examples

  9. Object and Collection Initializers

    Object and Collection Initializers - C#

  10. C# List Tutorial

    C# List Tutorial - Everything You Need To Learn About List ...

  11. C# List Examples

    C# List Examples

  12. C# Assignment Operators

    Here's a list of assignment operators in C#: Simple Assignment Operator (=): Assigns the value of the right-hand operand to the left-hand operand. int x = 10; Addition Assignment Operator (+=): Adds the value of the right-hand operand to the left-hand operand and assigns the result to the left-hand operand. int x = 5;

  13. C#

    C# - Assignment Operators

  14. ?? and ??= operators

    and ??= operators - null-coalescing operators - C# reference

  15. c#

    2. You can shorten your first example to listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name"; - Noah Heldman. Oct 9, 2012 at 23:17. 3. This is actually very useful. I was wondering how you can set more than one variable value at a time. My object has actually two variables I need to set in one pass.

  16. C# Sharp Programming Exercises, Practice, Solution

    C# Sharp programming Exercises, Practice, Solution

  17. c#

    some.List.Add("There!"); This form is only valid inside an object initializer, though - it's designed specifically for the case where you have a readonly field that you need to initialize using the object/collection initializer syntax. For example, this doesn't work: var some = new SomeObject(); some.List = { "Hi!", "There!"

  18. Addition operators

    Addition operators - + and += - C# reference

  19. Tylor Megill shines as Mets pass Braves in Wild Card race

    TORONTO -- It pays to have a Tylor Megill type around. Faced with a delay in Paul Blackburn's return from the injured list, the Mets gave Megill another start on Monday evening. The right-hander ran with the assignment, pitching a one-hit quality start in a 3-2 win over the Blue

  20. How can I initialize a C# List in the same line I declare it

    Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string. You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.

  21. Bitwise and shift operators (C# reference)

    Bitwise and shift operators (C# reference)

  22. Boolean logical operators

    Boolean logical operators - AND, OR, NOT, XOR