Learn A Tiny Bit Of C# In 7 Days - Day Six

Introduction

This is the sixth day of "Learn a Tiny Bit of C# in 7 days" In this series we will extend our topics try to cover basics of those topics.

What did we learn last time?

In the last article we covered the following topics:

  1. Reflection
  2. Early Binding/ Late Binding
  3. Stringbuilder/ System.String
  4. Var Keyword
  5. Extension Method
Before moving further let us focus on the previous article of the series:
Agenda for Day 6
  1. Partial classes
  2. Indexers
  3. Optional Parameter in C#
  4. Collection 
Partial classes
  1. Partial class allows us to split our class into two or more files. All these parts are then combined into a single class at compile time. The partial keyword is also applicable to Interface and Struct as well.

    Let’s try to implement them practically.

    Create a New Console Application.


                      Figure 1: Creating a new Console Application

    Add a new class Library to the solution,


                                        Figure 2: Creating a new Class Library


                            Figure 3: Name your new Class Library to Customer.

    Create the methods and properties of the Class,
    1. namespace Customer   
    2. {  
    3.     public class Customer   
    4.       
    5.     {  
    6.         //parametrized constructor    
    7.         public Customer(int customerId, string customerName, string customerAddress)   
    8.             {  
    9.                 this.Id = customerId;  
    10.                 this.Name = customerName;  
    11.                 this.Address = customerAddress;  
    12.             }  
    13.             //properties    
    14.         private int _Id;  
    15.         public int Id   
    16.       {  
    17.             get   
    18.             {  
    19.                 return _Id;  
    20.             }  
    21.             set  
    22.             {  
    23.                 _Id = value;  
    24.             }  
    25.         }  
    26.         private string _Name;  
    27.         public string Name  
    28.         {  
    29.             get  
    30.             {  
    31.                 return _Name;  
    32.             }  
    33.             set {  
    34.                 _Name = value;  
    35.             }  
    36.         }  
    37.         private string _Address;  
    38.         public string Address   
    39.         {  
    40.             get {  
    41.                 return _Address;  
    42.             }  
    43.             set {  
    44.                 _Address = value;  
    45.             }  
    46.         }  
    47.         /// <summary>    
    48.         /// Returns details of the Customer    
    49.         /// </summary>    
    50.         /// <returns>string</returns>    
    51.         public string PrintCustomerDetails()   
    52.         {  
    53.             return "The Details are Customer Id= " + Id + "Customer Name= " + Name + " Customer Address= " + Address;  
    54.         }  
    55.     }  
    56. }    
    When we want to use the class functionality we first add the reference of the class in console application and then create object of the class as shown below-


                               Figure 4: Referencing the customer class library.
    1. using System;  
    2. using CustomerClass;  
    3. namespace PartialClass   
    4. {  
    5.     class Program   
    6.     {  
    7.         static void Main(string[] args)   
    8.       {  
    9.             //creating instance of Customerclass    
    10.             Customer customer = new Customer(1, "Saillesh""Dehradun");  
    11.             string customerDetails = customer.PrintCustomerDetails();  
    12.             Console.WriteLine(customerDetails.ToString());  
    13.             Console.ReadLine();  
    14.         }  
    15.     }  
    16. }  
    Now let’s create a partial class. A partial class can be created with the help of a partial keyword. Partial keyword helps us to split our class in more than one file as shown below.

    Add a new class named CustomerPartialClass,

    Declare some properties in this class and declare this class as partial.

    Syntax - Partial Class ClassName
    1. namespace Customer   
    2. {  
    3.     partial class CustomerPartialClass  
    4.     {  
    5.         //properties    
    6.         private int _Id;  
    7.         public int Id   
    8.       {  
    9.             get   
    10.             {  
    11.                 return _Id;  
    12.             }  
    13.             set  
    14.             {  
    15.                 _Id = value;  
    16.             }  
    17.         }  
    18.         private string _Name;  
    19.         public string Name   
    20.         {  
    21.             get  
    22.             {  
    23.                 return _Name;  
    24.             }  
    25.             set  
    26.             {  
    27.                 _Name = value;  
    28.             }  
    29.         }  
    30.         private string _Address;  
    31.         public string Address   
    32.         {  
    33.             get {  
    34.                 return _Address;  
    35.             }  
    36.             set {  
    37.                 _Address = value;  
    38.             }  
    39.         }  
    40.     }  
    41. }  
    Now again create one more class,


                                  Figure 5: Creating a new CustomerPartialClass2

    Common definition will appear as shown below-
    1. namespace Customer  
    2. {  
    3. class CustomerPartialClass2  
    4. {  
    5. }  
    6. }  
    Change the name to the same as above declared partial class and create a parameterized constructor for the same as we have created in Customer Class.
    1. namespace Customer  
    2. {  
    3.     partial class CustomerPartialClass  
    4.     {  
    5.         public CustomerPartialClass(int id, string customerName, string customerAddress)   
    6.       {  
    7.             this._Id = id;  
    8.             this._Name = customerName;  
    9.             this._Address = customerAddress;  
    10.         }  
    11.     }  
    12. }   
    As soon as we try to access private properties in our second CustomerPartialClass we will see the intelisense window as shown below with all the properties.


    Figure 6: Demonstrating that private properties are accessible in the other Partial Class.

    Let’s create one more class and create the PrintCustomerDetails Method in it.
    1. namespace Customer  
    2. {  
    3.     partial class CustomerPartialClass  
    4.     {  
    5.         /// <summary>    
    6.         /// Returns details of the Customer    
    7.         /// </summary>    
    8.         /// <returns>string</returns>    
    9.         public string PrintCustomerDetails()  
    10.       {  
    11.             return "The Details are Customer Id= " + Id + "Customer Name= " + Name + " Customer Address= " + Address;  
    12.         }  
    13.     }  
    14. }  
    Now try to create instance of the CustomerPartialClass in our main program


    Figure 7: Demonstrating creating instance of Partial Class passing value to the constructor.

    Parameterized constructor. 
    1. using System;  
    2. using CustomerClass;  
    3. namespace PartialClass  
    4. {  
    5.     class Program   
    6.     {  
    7.         static void Main(string[] args)  
    8.       {  
    9.             //Creating instance CustomerPartialClass    
    10.             CustomerPartialClass customerPartialClass = new CustomerPartialClass(1, "Nishant""Lonavla");  
    11.             string customerDetails = customerPartialClass.PrintCustomerDetails();  
    12.             Console.WriteLine(customerDetails);  
    13.             Console.ReadLine();  
    14.         }  
    15.     }  
    16. }  

    Figure 8: Output Demonstrating calling PrintCustomerDetails from the partial class.

    Partial Classes real time example in asp.net web form in asp.net web forms visual studio uses partial classes to separate automatically generated code when we add a web form two files are created

    1 .aspx.cs
    2 .aspx.designer.cs


              Figure 9: Demonstrating partial class concept in ASP.NET Web Forms.



                                   Figure 10: Demonstrating partial class Default.


    .aspx.cs file contains the developer code that developers writes. While if we see .aspx.designer.cs it contains the code generated by the system i.e. if drag and drop any control the system generates the code eg-

    If I drag and drop the button control the system will generate the class for that control as shown below,

                            Figure 11: Demonstrating Code generated


                                  Figure 12:
    Demonstrating Code generated

    While in .aspx.cs we can write our code on button click etc. as shown below-


                                        Figure 13:
    Our Events code.

    Same we can see in windows form application as well.

    Advantages of using Partial Classes

    When we are working in a project and we want to finish it as early as possible then we can create partial classes and share the functionality of class among the developers

    When working with automatically generated code eg asp.net webforms, windows form application, entity framework data model etc.

    Partial Methods

    Partial methods are created using a partial keyword. Now for this demo we will use our Partial class project.

    Syntax - partial void Details();

    Demo
    1. using System;  
    2. namespace CustomerClass  
    3. {  
    4.     public partial class CustomerPartialClass   
    5.     {  
    6.         public CustomerPartialClass(int id, string customerName, string customerAddress)  
    7.       {  
    8.                 this._Id = id;  
    9.                 this._Name = customerName;  
    10.                 this._Address = customerAddress;  
    11.             }  
    12.             //Partial class Declaration with no definition    
    13.         partial void Details();  
    14.         public void Method()   
    15.       {  
    16.             Console.WriteLine("Calling partial method");  
    17.             Details();  
    18.         }  
    19.     }  
    20. }  
    If we try to compile the project we will get no errors and if we run our program we will get a below output.


                   Figure 14:
    Demonstrating the partial class and partial method.

    What we learned

  • If we just declare a partial method without the definition it will get compiled without any error.
  • If we try to call the partial method with no definition compiler will remove the signature and call to that method( Implementation of partial method is optional).

    Now let’s implement the definition of the partial method in another partial class CustomerPartialClass as shown below,
    1. using System;  
    2. namespace CustomerClass  
    3. {  
    4.     public partial class CustomerPartialClass   
    5.     {  
    6.         //properties    
    7.         private int _Id;  
    8.         public int Id  
    9.         {  
    10.             get  
    11.             {  
    12.                 return _Id;  
    13.             }  
    14.             set   
    15.             {  
    16.                 _Id = value;  
    17.             }  
    18.         }  
    19.         private string _Name;  
    20.         public string Name   
    21.         {  
    22.             get  
    23.             {  
    24.                 return _Name;  
    25.             }  
    26.             set   
    27.             {  
    28.                 _Name = value;  
    29.             }  
    30.         }  
    31.         private string _Address;  
    32.         public string Address  
    33.         {  
    34.             get  
    35.             {  
    36.                 return _Address;  
    37.             }  
    38.             set  
    39.             {  
    40.                 _Address = value;  
    41.             }  
    42.         }  
    43.         partial void Details()  
    44.         {  
    45.             Console.WriteLine("Partial Method Details definition");  
    46.             Console.WriteLine("The Details are Customer Id= " + Id + "Customer Name= " + Name + " Customer Address= " + Address);  
    47.         }  
    48.     }  
    49. }  
    Now if we try to call the Partial Method we will get the appropriate output as shown below-


                Figure 15: Demonstrating the partial class and partial method.

    Note*

  • Partial method are by default private.
  • You cannot apply access modifiers on partial methods.
  • Signature of the partial class declaration must match with partial class implementation.
  • Partial method should be declared inside a Partial class or structure i.e. we cannot define partial class inside a non-partial class.
  • We cannot have multiple implementation.
  1. Indexers

    1. Indexers help us to access the collection present within a class. In .net we use Indexers to retrieve data from session state and application state. Indexer allow our class to be like an array i.e. as we access the value of an array Array[2] in the same way we can access the value in our class.

      Indexer are kind of properties but they accept parameters.

      Eg - Let take an example of a List of Integer type
      1. List<int> listInt = new List<int>();  
      2. for(int i=1;i<50;i++)  
      3. {  
      4. listInt.Add(i);  
      5. }  
      Here I am adding numbers from 1 to 49 to the list. Once we are done with adding the list of integers we will try to access the last element of the list the same way we do in array.

                             Figure 16: Demonstrating the input type of Indexer.

      We can see as soon as I press [. The intellisense show me the input type for this index, it is asking me the index which I want to retrieve. So I will enter 48, as shown below and check the output on the screen.


                          Figure 17: Output after calling Indexer.

      If we go to List definition we will find the index as shown below-

      We can see that this indexer has get and set accessors i.e. indexer can have get and set accessors same as properties. Let’s try to implement the same in demo.

      We will have a one to many relationship i.e. one customer that can have multiple addresses.

      I will be using entity framework in order to retrieve data from database using code first approach.

      So we first create our Database Tables.

    • We will create a Table named TblCustomer with following columns as shown in figure.


                 Figure 18: Table design of TblCustomer.

    • Second table named TblAddress with following mentioned Columns.

               Figure 19: Table design of TblAddress.

      Records present in table tblCustomer

           Figure 20: Records in table TblCustomer.

                     Figure 21: Records in table tblAddress.
    • Now let’s create our classes,
      1. public class Customer  
      2. {  
      3.     public int Id   
      4.     {  
      5.         get;  
      6.         set;  
      7.     }  
      8.     public String Name   
      9.     {  
      10.         get;  
      11.         set;  
      12.     }  
      13.     [ForeignKey("AddressId")]  
      14.     public virtual List < Address > Addresses  
      15.     {  
      16.         get;  
      17.         set;  
      18.     }  
      19. }  
      20. public class Address  
      21. {  
      22.     public int AddressId  
      23.     {  
      24.         get;  
      25.         set;  
      26.     }  
      27.     public int pincode   
      28.     {  
      29.         get;  
      30.         set;  
      31.     }  
      32.     public string building  
      33.     {  
      34.         get;  
      35.         set;  
      36.     }  
      37.     public string area  
      38.     {  
      39.         get;  
      40.         set;  
      41.     }  
      42. }  
      Now we will create our DAL which will communicate with DB server,
      1. public class DAL: DbContext  
      2. {  
      3.     //Dbcontext class will give all the DB related features to DAL Class    
      4.     //DbSet is a gel code that act as a gel between our model classes and tables    
      5.     public DbSet < Customer > customers  
      6.     {  
      7.         get;  
      8.         set;  
      9.     }  
      10.     public DbSet < Address > address  
      11.     {  
      12.         get;  
      13.         set;  
      14.     }  
      15.     protected override void OnModelCreating(DbModelBuilder modelBuilder)   
      16.     {  
      17.         //mapping our model entity with tables    
      18.         modelBuilder.Entity < Customer > ().ToTable("TblCustomer");  
      19.         modelBuilder.Entity < Address > ().ToTable("TblAddress");  
      20.     }  
      21. }    
      Now in app.config add the connection string,
      1. <add name="DAL" connectionString="Data Source=.;Initial Catalog=EnitySample;Integrated Security=True" providerName="System.Data.SqlClient"/>  
      Now we will create a simple indexer which will take pincode as input and will return the area based on the pincode passed.
      1. public string this[int pincode]   
      2. {  
      3.     get  
      4.     {  
      5.         //Db context object creation    
      6.         DAL _context = new DAL();  
      7.         //Linq query for retrieving single area based on passed pincode    
      8.         return _context.address.Single(add => add.pincode == pincode).area;  
      9.     }  
      10. }    
      Here as we can see how simple and easy it’s to create index. We just have to write the input parameter. Return type and get or set methods whichever is required.

      So let’s try to run our program and retrieve an area with the help of Indexer.
      1. namespace Indexer  
      2. {  
      3.     class Program   
      4.     {  
      5.         static void Main(string[] args)  
      6.         {  
      7.             Customer customer = new Customer();  
      8.             //Calling indexer and passing the pincode    
      9.             Console.WriteLine(customer[248001]);  
      10.             Console.ReadLine();  
      11.         }  
      12.     }  
      13. }   
      Let’s run our application,


                         Figure 22: Demonstrating implementation of Indexer using EF.

      Breakpoints hits on the Indexer and parameter has been passed to the indexer. Now DAL object will be created and it will be responsible for retrieving single area based on the passed pincode by the user.


                           Figure 23: Output to the screen.

      As we can see the retrieved area from the db. Let try set accessor and in set accessor we will pass the pincode and based upon that pincode passed we will set the area passed by the user as shown below-
      1. set  
      2. {  
      3. DAL _context = new DAL();  
      4.   
      5. _context.address.Single(add => add.pincode == pincode).area = value;  
      6.   
      7. }  
      Now we will call the set accessor when we want to set the area based on the pin code passed by the user.


                  Figure 24: Saving the new value to the database using Indexer.

      Once the area is found,


                     Figure 25: Saving the new value to the database using Indexer.

      Once the save changes happen we will retrieve the updated area once we call the get indexer as shown below


                        Figure 26: Retrieving the saved value from the database.

      Retrieving get indexer.


                                          Figure 27: Output

      Now here we can see the updated value retrieved from the get indexer.

      Few point to be note down

      a. Use This keyword to create an indexer.
      b. Indexer can have get and set properties.

      Overloading Indexer,

      I hope all of you will be aware of Overloading feature in csharp the concept of overloading is also implemented in indexer which means we can have more than one indexer with same name but with different numbers of parameter and type.

      Let overload and Indexer now in our overloaded indexer we will create an indexer which will return the name of the customer based on the Customer Id passed as shown below-


                                       Figure 28: Overloading Constructor.

      Showing two overloads one takes pincode while other takes Empid and Name.


                                       Figure 29: Overloading Constructor.

      Let’s run our Application.

      Breakpoint hit and we have passed empId and Name,


                        Figure 30: Executing Indexer with two parameter.


                                             Figure 31: Output.

      We can see the desired output on the screen.

  2. Optional Parameter in C#

    1. Use Parameter arrays
    2. Use OptionalAttribute
       
     
    Optional parameter is beneficial when we want to create a single method that is able to perform operations based on the no of inputs passed by the User.
     
    Parameter Arrays (Params)

    Params keyword allows our method to receive variable numbers of input parameter. The word params is to be used with arrays and it allows us to pass as many numbers of parameters with declaring an array. Params declaration is required in the method declaration or we can say signature. With params, the arguments passed to a method are changed by the compiler to elements in a temporary array.

    Syntax - public void MethodName(Params object[]objectArray)

    We can call the method

    MethodName(123,’Learn Tiny bit of C# in 7 days’,”day 6”);

    Let’s try to unleash it practically.
    1. using System;  
    2. namespace ParmeterLessMethod   
    3. {  
    4.     class Program  
    5.     {  
    6.         
    7.         static void Main(string[] args)  
    8.         {  
    9.                 //calling Sum method and passing the values    
    10.                 Sum(10, 20, 20, 30);  
    11.             }  
    12.             /// <summary>    
    13.             /// Sum method performs Addition operation    
    14.             /// </summary>    
    15.             /// <param name="number1">in</param>    
    16.             /// <param name="number2"></param>    
    17.             /// <param name="restofNumbers">Params contain the array of input parameters</param>    
    18.         public static void Sum(int number1, int number2, params int[] restofNumbers)  
    19.         {  
    20.             int Result = number1 + number2;  
    21.             if (restofNumbers != null) {  
    22.                 foreach(int num in restofNumbers)  
    23.                 {  
    24.                     Result += num;  
    25.                 }  
    26.             }  
    27.             Console.WriteLine("The sum result is " + Result);  
    28.             Console.ReadLine();  
    29.         }  
    30.     }  
    31. }  

             Figure 32:
    Demonstrating Optional Parameter in C#.

    Params keyword should always be last parameters.


                Figure 33:
    Demonstrating Optional Parameter should always be last.

    Params can only take single dimension array.


    Figure 34:
    Demonstrating Optional Parameter param only takes single dimensional array.

    Optional Attribute Class

    Optional Attribute Class is present in System.Runtime.InteropServices. OptionalAttribute is used to indicate that a parameter is optional.
    1. using System;  
    2. using System.Runtime.InteropServices;  
    3. namespace OptionalAttributeSample   
    4. {  
    5.     class Program   
    6.     {  
    7.         static void Main(string[] args)   
    8.         {  
    9.                 Multiplication(10, 20);  
    10.             }  
    11.             /// <summary>    
    12.             /// Multiplication method to multiplies minimum two numbers    
    13.             /// </summary>    
    14.             /// <param name="num1">mandatory num int</param>    
    15.             /// <param name="num2">mandatory num int</param>    
    16.             /// <param name="restOfNumbers">Optional Parameter</param>    
    17.         public static void Multiplication(int num1, int num2, [Optional] int[] restOfNumbers) {  
    18.             int result = num1 * num2;  
    19.             if (restOfNumbers != null)  
    20.             {  
    21.                 foreach(int num in restOfNumbers)  
    22.                 {  
    23.                     result *= num;  
    24.                 }  
    25.             }  
    26.             Console.WriteLine("Multiplication is =" + result);  
    27.             Console.ReadLine();  
    28.         }  
    29.     }  
    30. }  
    Output


           Figure 35: Demonstrating Optional attribute class.

    Here we need to pass the int array rather than parameters as in Param keyword as shown below-

    If we try to just pass the parameter we get the compile time error as shown below-


                   Figure 36:
    Demonstrating Optional attributeonly accepts array.

    Passing an array
    1. using System;  
    2. using System.Runtime.InteropServices;  
    3. namespace OptionalAttributeSample  
    4. {  
    5.     class Program   
    6.     {  
    7.         static void Main(string[] args)   
    8.       {  
    9.                 Multiplication(10, 20, new int[]  
    10.                 {  
    11.                     1,  
    12.                     2,  
    13.                     3  
    14.                 });  
    15.             }  
    16.             /// <summary>    
    17.             /// Multiplication method to multiplies minimum two numbers    
    18.             /// </summary>    
    19.             /// <param name="num1">mandatory num int</param>    
    20.             /// <param name="num2">mandatory num int</param>    
    21.             /// <param name="restOfNumbers">Optional Parameter</param>    
    22.         public static void Multiplication(int num1, int num2, [Optional] int[] restOfNumbers)  
    23.       {  
    24.             int result = num1 * num2;  
    25.             if (restOfNumbers != null)   
    26.             {  
    27.                 foreach(int num in restOfNumbers)  
    28.                 {  
    29.                     result *= num;  
    30.                 }  
    31.             }  
    32.             Console.WriteLine("Multiplication is =" + result);  
    33.             Console.ReadLine();  
    34.         }  
    35.     }  
    36. }  
    Output


    Figure 37:
    Multiplication operation using Optional attribute class..

  3. Collection

    Collections are the group of records/ related objects that can be termed as a one logical unit. If the number of elements are dynamic i.e. we are not aware of the no of records than we should use collection class instead of Array.

    Eg.


    Customer Collection

      1.Customer Id
      2.Customer Name
      3.Customer Address
      4.Customer MobileNo
         Let’s try to unleash them one by one.
  • Index Based

    Index Based as the name specify the Index Based collection helps you to access the row of the collection by the help of the generated index. Index based collection are of two types-

    a. Array
    b. List

    Eg-
    1. //Index Based collection   
    2. //declaring an Array of type string  
    3.   
    4. string[] names = new string[7];  
    5. names[0] = "Learn";  
    6. names[1] = "Tiny";  
    7. names[2] = "Bit";  
    8. names[3] = "of";  
    9. names[4] = "C#";  
    10. names[5] = "6th";  
    11. names[6] = "day";  
    12. //Now i want to access the value or record i will use the index   
    13. Console.WriteLine("The value of index 0 is"+names[0].ToString() );  
    14. Console.ReadLine();  
    Using List
    1. //Index Based collection   
    2. //declaring a list of type string  
    3.   
    4. List<string> lString = new List<string>();  
    5. lString.Add("Learn");  
    6. lString.Add("Tiny");  
    7. lString.Add("Bit");  
    8. lString.Add("of");  
    9. lString.Add("C#");  
    10. lString.Add("6th");  
    11. lString.Add("day");  
    12.   
    13. //Now i want to access the value or record i will use the index   
    14. Console.WriteLine("The value of list for index 0 is " +lString[0].ToString());  
    15. Console.ReadLine();  
    List<T> Type collection can be compared with each other. But in c# we have wide variety of collections.

    Most of the collection can be found in the system.collection and system.collection.generics. The system.collection.generics contains the generic collection.

    Lists - A list collection can be used to create a collection of any type i.e. we can create a list of string, double or even complex types (classes). The object stored in the list can be accessed via index.

    Let’s take a class called cricketer which has following properties
    1. namespace Sample  
    2. {  
    3. public class Cricketer  
    4. {  
    5. public int Id { getset; }  
    6. public string Name { getset; }  
    7. public string Country { getset; }  
    8. }  
    9. }  

                         Figure 38: Demonstrating List as a Strongly Typed.

    When we declare a List it asks for the Type i.e. string, int, complex type class. Here we are going to create a list of type Cricketer i.e. complex type.

    Syntax-

    List<Cricketer> lCricketers = new List<Cricketer>();
    var lCricketers =new List<Cricketer>();


                                           Figure 39: Creating list with n limit.

    There are three overloaded constructors to create a list.

        1 As stated above in Syntax where it doesn’t take any values.
        2 Passing a length/capacity of the List as shown below.


                         Figure 40: Demonstrating List with a capacity.
    1. List<Cricketer> lCricketers = new List<Cricketer>(2);  
    Which means the lCricketers can take only 2 records of Cricketer.


                            Figure 41: Demonstrating creating instance of a list.

    Adding elements to a List:

    You can add elements to the using Add method as shown below,
    1. static void Main(string[] args)  
    2. {  
    3.     //creating Customer object    
    4.     Cricketer cricketer = new Cricketer()  
    5.     {  
    6.         Id = 1,  
    7.             Country = "India",  
    8.             Name = "Virat Kohli"  
    9.     };  
    10.     //creating Customer object    
    11.     Cricketer cricketer2 = new Cricketer()  
    12.     {  
    13.         Id = 1,  
    14.             Country = "India",  
    15.             Name = "Virat Kohli"  
    16.     };  
    17.     List < Cricketer > lCricketers = new List < Cricketer > ();  
    18.     lCricketers.Add(cricketer);  
    19.     lCricketers.Add(cricketer2);  
    20. }  
    Retrieving an item from a list-
    1. Cricketer player = lCricketers[0];  
    2. Console.WriteLine("Player Details are as follows ID={0},Name={1},Country={2}",player.Id,player.Name,player.Country);  
    3. Console.ReadLine();  

    Figure 42: Demonstrating Retrieving an item from a list with index 0.

    //Iterating threw all the list

    Using Foreach Loop
    1. //iterating threw all Customer  
    2. Console.WriteLine("Players Details");  
    3. foreach (Cricketer player in lCricketers)  
    4. {  
    5.   
    6. Console.WriteLine("Player Details are as follows ID={0},Name={1},Country={2}", player.Id, player.Name, player.Country);  
    7.   
    8. }  
    9. Console.ReadLine();  
    Output


                            Figure 43:
    Looping threw the list.

    Using for loop
    1. //iterating threw all Customer using for loop  
    2. Console.WriteLine("Players Details");  
    3. for(int i=0;i<lCricketers.Count;i++)  
    4. {  
    5. Console.WriteLine("Player Details are as follows ID={0},Name={1},Country={2}", lCricketers[i].Id, lCricketers[i].Name, lCricketers[i].Country);  
    6. }  
    7.   
    8. Console.ReadLine();  
    Output


                 Figure 44:
    Looping threw the list using for loop.

    In a list we cannot add object of different type which means we can add only object of type Cricketer as shown below:


          Figure 45: Demonstrating that we can add only object of type Cricketer.

    What if we try to add an object which implements the Cricketer Class?  Let’s try practically

    Let’s create a class Umpire and inherit from Cricketer class,
    1. public class Umpire:Cricketer  
    2. {  
    3. //all the properties will be accessible for the Umpire object  
    4.   
    5. }  
    Now let’s try to add Umpire object to the Cricketer list
    1. Umpire umpire = new Umpire()  
    2. {  
    3.   
    4. Id=5,  
    5. Country="New Zealand",  
    6. Name="Billi Bowden",  
    7. };  
    8.   
    9. lCricketers.Add(umpire);  
    Output


              Figure 46: Demonstrating that we can add object of derive class.

    Inserting the type to the defined index in the list

    We can insert the type in the list at the defined position by us by using Insert function of list as shown below-
    1. Cricketer cricketer3 = new Cricketer()  
    2. {  
    3. Id = 3,  
    4. Country = "India",  
    5. Name = "Sir Jadeja"  
    6.   
    7. };  
    8.   
    9. //adding the cricketer3 to the defined index in the list  
    10. lCricketers.Insert(0, cricketer3);  


             Figure 47:
    Demonstrating inserting the object to the desired index.

    We can clearly see the index of the added Cricketer object to the desired position specified by us. I.e. at 0 index. When we insert the object at specific position all the objects are pushed forward of their index.

    Functions in the List

    Contains - Contains function check if item exists in the list and if it does it returns true else false.

    Create a Simple Student class
    1. class Student   
    2. {  
    3.     public int Id   
    4.     {  
    5.         get;  
    6.         set;  
    7.     }  
    8.     public string Name   
    9.     {  
    10.         get;  
    11.         set;  
    12.     }  
    13.     public string MobileNo   
    14.     {  
    15.         get;  
    16.         set;  
    17.     }  
    18. }  
    19. class Program {  
    20.     static void Main(string[] args)   
    21.     {  
    22.         List < Student > students = new List < Student > ();  
    23.         Student stud1 = new Student   
    24.         {  
    25.             Id = 1,  
    26.                 Name = "Saillesh",  
    27.                 MobileNo = "9012134556"  
    28.         };  
    29.         students.Add(stud1);  
    30.         Student stud2 = new Student   
    31.         {  
    32.             Id = 2,  
    33.                 Name = "Raul",  
    34.                 MobileNo = "8012134256"  
    35.         };  
    36.         students.Add(stud2);  
    37.         Student stud3 = new Student   
    38.         {  
    39.             Id = 3,  
    40.                 Name = "Rohit",  
    41.                 MobileNo = "7012134556"  
    42.         };  
    43.         students.Add(stud3);  
    44.         Student stud4 = new Student   
    45.         {  
    46.             Id = 4,  
    47.                 Name = "Rakesh",  
    48.                 MobileNo = "9012134616"  
    49.         };  
    50.         students.Add(stud4);  
    51.         //checking if the stud4 Rakesh exist in the list    
    52.         if (students.Contains(stud4))   
    53.         {  
    54.             Console.WriteLine("Rakesh Exists in the list");  
    55.         } else   
    56.         {  
    57.             Console.WriteLine("Rakesh doesn't Exists in the list");  
    58.         }  
    59.     }  
    60. }  

            Figure 48:
    Demonstrating Contains method.

    If you want to check whether student exists in a list using a lambda expression you need to use Exists Function as shown below:

    Exists - function checks if item exists in the list or not based upon a condition and returns respective true or false for the same.

    We will use same class as shown in Contains demo.

    Check the student whose id is 4,
    1. //checking for exists  
    2.   
    3. if (students.Exists(stud => stud.Id == 4))  
    4. {  
    5. Console.WriteLine("Rakesh Exists in the list");  
    6.   
    7. }  
    8. else  
    9. {  
    10. Console.WriteLine("Rakesh doesn't Exists in the list");  
    11. }  
    Output


            Figure 49:
    Demonstrating Exists method.

    Find Function - This function matches for the condition and return the first item from the list.

    Add one more student object to the list.
    1. Student stud5 = new Student   
    2. {  
    3.     Id = 5,  
    4.         Name = "Rakesh",  
    5.         MobileNo = "9997373111"  
    6. };  
    7. students.Add(stud5);  
    8. //Find method returns the first item matching condition     
    9. Student student = students.Find(stud => stud.Name == "Rakesh");  
    10. Console.WriteLine("The details of Student retrieved from list are");  
    11. Console.WriteLine("Student id {0} \nStudent Name {1} \nStudent MobileNo {2}", student.Id, student.Name, student.MobileNo);  
    Output


                Figure 50:
    Printing the details of student after Find function.

    FindLast - FindLast function search for the element that matches the condition defined in the lambda expression and returns the last occurrence in the list.
    1. //FindLast method returns the last item from the list based on matching condition  
    2. Student student = students.FindLast(stu => stu.Name == "Rakesh");  
    3. Console.WriteLine("The details of Student retrieved from list are");  
    4. Console.WriteLine("Student id {0} \nStudent Name {1} \nStudent MobileNo {2}",student.Id,student.Name,student.MobileNo);  

             Figure 51:
    Printing the details of student after FindLast function.

    FindAll - FindAll function searches for the elements that match the condition defined in the lambda expression and returns all the occurrences in the list.
    1. //retrieving all the items whose Name is Rakesh  
    2. var studentLst = students.FindAll(stu => stu.Name == "Rakesh");  
    3. foreach(Student stu in studentLst)  
    4. {  
    5. Console.WriteLine("The details of Student retrieved from list are");  
    6. Console.WriteLine("Student id {0} \nStudent Name {1} \nStudent MobileNo {2}", stu.Id, stu.Name, stu.MobileNo);  
    7. }  
    Output


             Figure 52:
    Printing the details of student after FindAll function.


Similar Articles