How To Get And Set An Item In A C# List

C# List<T> class provides methods and properties to create a list of objects (classes).
 
List is a generic class. You must import the following namespace before using the List<T> class.
  1. using System.Collections.Generic;  
List.Item
 
The Item property gets and sets the value associated with the specified index.
 
The following code snippet gets and sets the first item in a list.
  1. using System;  
  2. using System.Collections.Generic;  
  3. namespace ConsoleApp1  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Create a list of strings    
  10.             List<string> AuthorList = new List<string>();  
  11.             AuthorList.Add("Mahesh Chand");  
  12.             AuthorList.Add("Praveen Kumar");  
  13.             AuthorList.Add("Raj Kumar");  
  14.             AuthorList.Add("Nipun Tomar");  
  15.             AuthorList.Add("Dinesh Beniwal");  
  16.   
  17.             // Get first item of a List     
  18.             string auth = AuthorList[0];  
  19.             Console.WriteLine(auth);  
  20.             Console.WriteLine("-------------");  
  21.             // Set first item of a List    
  22.             AuthorList[0] = "New Author";  
  23.             foreach (var author in AuthorList)  
  24.             {  
  25.                 Console.WriteLine(author);  
  26.             }  
  27.         }  
  28.     }  
  29. }  
The output from above code listing is shown in below figure.
 
 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.