Array List

What is Array List?

ArrayList is a non-generic type of collection in C#. It can contain elements of any data types. It is similar to an array, except that it grows automatically as you add items in it. Unlike an array, you don't need to specify the size of ArrayList.

the ArrayList class implements IEnumerable, ICollection, and IList interfaces. So, you can create an object of ArrayList class and assign it to the variable of any base interface type. However, if you assign it to IEnumerable or ICollection type variable then you won't be able to add elements and access ArrayList by index.

For Ex:

     class CollectionExamples
    {
        static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();//can add elements with additional methods
            IList _ArrayIList = new ArrayList();//can add elements
            ICollection _ArrayICollection = new ArrayList();//can not add elements
            IEnumerable _ArrayIEnumerable = new ArrayList();//can not add elements

      
        }
    }

From above example you can see that using ArrayList is more useful compare to others.because ArrayList class contains some additional methods which are not the members of IList interface such as AddRange(), BinarySearch(), Repeat(), Reverse(), etc.

Properties of ArrayList

  1. Capicity: Gets or sets the number of elements that the ArrayList can contain
  2. Count:Gets the number of elements actually contained in the ArrayList.
  3. IsFixedSize: Gets a value indicating whether the ArrayList has a fixed size.
  4. IsReadOnly: Gets a value indicating whether the ArrayList is read-only.
  5. Item:Gets or sets the element at the specified index.

Methods Of ArrayList

1.Add()/AddRange: Add() method adds single elements at the end of ArrayList.
AddRange() method adds all the elements from the specified collection into ArrayList

 Example:

class CollectionExamples
    {
        static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();
            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);

            _ArrayList2.AddRange(_ArrayList);//Adding entire collection

            Console.WriteLine("Array List 1 Count {0}", _ArrayList.Count);
            Console.WriteLine("Array Lisr 2 Count {0}", _ArrayList2.Count);
            Console.ReadLine();

        }
    }
                                                                                                                                                            




2.Insert()/InsertRange():

Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting from specified index in ArrayList.       

Example:   

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);
            _ArrayList.Insert(1, "Inserted"); // Inserted Single item at particular index

            _ArrayList2.AddRange(_ArrayList);
            _ArrayList2.InsertRange(3,_ArrayList); //Insert entire list from the particular index.

            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            foreach (var i in _ArrayList2)
            {
                Console.WriteLine("Items in ArrayList - 2 {0}", i);
            }
            Console.WriteLine("Array List 1 Count {0}", _ArrayList.Count);
            Console.WriteLine("Array Lisr 2 Count {0}", _ArrayList2.Count);
            Console.ReadLine();

        }
    }
    
                                                                                                                                                            

3.Remove()/Remove Range():
Remove() method removes the specified element from the ArrayList.
RemoveRange() method removes a range of elements from the ArrayList.

  static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);
            _ArrayList.Remove(1); //Remove 1 from Arraylist


            _ArrayList2.AddRange(_ArrayList);
            _ArrayList2.Add("New Values");
            _ArrayList2.RemoveRange(0,3);//Remove 3 element starting from 0th.
          

            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            foreach (var i in _ArrayList2)
            {
                Console.WriteLine("Items in ArrayList - 2 {0}", i);
            }
            Console.WriteLine("Array List 1 Count {0}", _ArrayList.Count);
            Console.WriteLine("Array Lisr 2 Count {0}", _ArrayList2.Count);
            Console.ReadLine();

        }

                                                                                                                                                        


4.RemoveAt():

Removes the element at the specified index from the ArrayList.

Example  

static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
            ArrayList _ArrayList2 = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add("Two");
            _ArrayList.Add(2.5);
            _ArrayList.Add(3.5f);
            _ArrayList.RemoveAt(2); //Remove 2 index element from Arraylist

            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
 
            Console.ReadLine();

        }
                                                                                                                                                         

5.Sort & Reverse():

The ArrayList class includes Sort() and Reverse() method. The Sort() method arranges elements in ascending order. However, all the elements should have same data type so that it can compare with default comparer otherwise it will throw runtime exception.

The Reverse() method arranges elements in reverse order. Last element at zero index and so on.

Example:

   static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();
         

            _ArrayList.Add(1);
            _ArrayList.Add(2);
            _ArrayList.Add(2);
            _ArrayList.Add(3);
            
            _ArrayList.Sort(); // Sorting
            foreach(var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            _ArrayList.Reverse(); //Reverse
            foreach (var i in _ArrayList)
            {
                Console.WriteLine("Items in ArrayList - 1 {0}", i);
            }
            Console.ReadLine();

        }                                                                                                                                                            


6.Contains

The Contains() method checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false.

Example:

 static void Main(string[] args)
        {
            ArrayList _ArrayList = new ArrayList();

            _ArrayList.Add(1);
            _ArrayList.Add(2);
            _ArrayList.Add(2);
            _ArrayList.Add(3);
         
            _ArrayList.Sort();
            Console.WriteLine(_ArrayList.Contains(3)); //Print true
            Console.ReadLine();

        }


C# Types of classes.

Hello friends,
Here we will discuss on types of classes in c#.

There are four different types of classes available in C#. They are as follows:

1. Static class
2. Abstract class
3. Partial class
4. Sealed class

Static class:

A class with static keyword that contains only static members is defined as static class. A static class cannot be instantiated.

Characteristics of static class

  • Static class cannot instantiated using a new keyword.
  • Static items can only access other static items. For example, a static class can only contain static members, e.g. variable, methods etc.
  • A static method can only contain static variables and can only access other static items.
  • Static items share the resources between multiple users.
  • Static cannot be used with indexers, destruction or types other than classes.
  • A static constructor in a non-static class runs only once when the class is instantiated for the first time.
  • A static constructor in a static class runs only once when any of its static members accessed for the first time.
  • Static members are allocated in a high frequency heap area of the memory.


Abstract class

A class with abstract modifier indicate that class is abstract class. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

Characteristic of Abstract class

  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessorizes.
  • It is not possible to modify an abstract class with the sealed modifier because the two modifiers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.


Partial class

  • The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.

Characteristic of Partial class

  • All the partial class definitions must be in the same assembly and namespace.
  • All the parts must have the same accessibility like public or private, etc.
  • If any part is declared abstract, sealed or base type then the whole class is declared of the same type.
  • Different parts can have different base types and so the final class will inherit all the base types.
  • The Partial modifier can only appear immediately before the keywords class, struct, or interface.
  • Nested partial types are allowed.


Sealed class

A class with sealed keyword indicates that class is sealed to prevent inheritance. Sealed class cannot inheritance.

C# Overview



C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).

C# was developed by Anders Hejlsberg and his team during the development of .Net Framework.

C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures.

The following reasons make C# a widely used professional language −
  • It is a modern, general-purpose programming language
  • It is object oriented.
  • It is component oriented.
  • It is easy to learn.
  • It is a structured language.
  • It produces efficient programs.
  • It can be compiled on a variety of computer platforms.
  • It is a part of .Net Framework.

Strong Programming Features of C#


Although C# constructs closely follow traditional high-level languages, C and C++ and being an object-oriented programming language. It has strong resemblance with Java, it has numerous strong programming features that make it endearing to a number of programmers worldwide.

Following is the list of few important features of C# −
  • Boolean Conditions
  • Automatic Garbage Collection
  • Standard Library
  • Assembly Versioning
  • Properties and Events
  • Delegates and Events Management
  • Easy-to-use Generics
  • Indexers
  • Conditional Compilation
  • Simple Multithreading
  • LINQ and Lambda Expressions
  • Integration with Windows


Before we study basic building blocks of the C# programming language, let us look at a bare minimum C# program structure so that we can take it as a reference in upcoming chapters.
Creating Hello World Program

A C# program consists of the following parts −

  • Namespace declaration
  • A class
  • Class methods
  • Class attributes
  • A Main method
  • Statements and Expressions
  • Comments
Let us look at a simple code that prints the words "Hello World" −
using System;
namespace MyFirstApplication 
     class Program 
    { 
       static void Main(string[] args)
      {
           Console.WriteLine("Hello World");
           Console.ReadKey();
      } 
 }
}


Let us look at the various parts of the given program −


The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements.

The next line has the namespace declaration. A namespace is a collection of classes. The MyFirstApplication namespace contains the class Program.

The next line has a class declaration, the class Program contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the Program class has only one method Main.


The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed.

The Main method specifies its behavior with the statement Console.WriteLine("Hello World");

WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.


The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.

It is worth to note the following points −

  • C# is case sensitive.
  • All statements and expression must end with a semicolon (;).
  • The program execution starts at the Main method.
  • Unlike Java, program file name could be different from the class name.

C# Program to find number of occurence from a character in string

Hi, Below program is for getting number of occurrence from a given string.    

 class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter String: ");
            string input = Console.ReadLine();
            while (input.Length > 0)
            {
                Console.Write(input[0] + " : ");
                int count = 0;
                for (int j = 0; j < input.Length; j++)
                {
                    if (input[0] == input[j])
                    {
                        count++;
                    }
                }
                Console.WriteLine(count);
                input = input.Replace(input[0].ToString(), string.Empty); //Remove matched character
            }
            Console.ReadLine();
        }
    }

Output:
Enter String: csharpprogram
c : 1
s : 1
h : 1
a : 2
r : 3
p : 2
o : 1
g : 1
m : 1

C# Program for addition of two same size matrix

Hello friends, Below program is for creating two 2D Array and do addition of them. You can do multiplication,substation as same way.

Hope it will be useful for you,

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter size of matrix - ");
            int MatrixSize1 = Convert.ToInt32(Console.ReadLine());
            int[,] Array_1 = new int [MatrixSize1, MatrixSize1];
            int[,] Array_2 = new int[MatrixSize1, MatrixSize1];
            int[,] Array_3 = new int[100, 100];
            int i, j;

            Console.WriteLine("\n");
            Console.WriteLine("Enter values for matrix 1");
            for(i = 0; i < MatrixSize1; i++)
            {
                for(j = 0; j < MatrixSize1; j++)
                {
                    Console.Write("First Matrix element - [{0},{1}]:", i, j);
                    Array_1[i,j] = Convert.ToInt32(Console.ReadLine());
                }
            }
            Console.WriteLine("\n");
            for (i = 0; i < MatrixSize1; i++)
            {
                for (j = 0; j < MatrixSize1; j++)
                {
                    Console.Write("Second Matrix element - [{0},{1}]:", i, j);
                    Array_2[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }

            Console.WriteLine("\n");
            Console.WriteLine("Values inserted in Matrix 1");
            for (i = 0; i < MatrixSize1; i++)
            {
                Console.WriteLine("");
                for (j = 0; j < MatrixSize1; j++)
                {
                    Console.Write("{0}\t", Array_1[i, j]);
                }
            }

            Console.WriteLine("\n");
            Console.WriteLine("Values inserted in Matrix 2");
            for (i = 0; i < MatrixSize1; i++)
            {
                Console.WriteLine("");
                for (j = 0; j < MatrixSize1; j++)
                {
                    Console.Write("{0}\t", Array_2[i, j]);
                }
            }

            Console.WriteLine("\n");
            Console.WriteLine("Sum of Two Matrix");
            for (i = 0; i < MatrixSize1; i++)
            {
                for (j = 0; j < MatrixSize1; j++)
                {
                    Array_3[i, j] = Array_1[i, j] + Array_2[i, j];
                }
            }

            for (i = 0; i < MatrixSize1; i++)
            {
                Console.WriteLine("");
                for (j = 0; j < MatrixSize1; j++)
                {
                    Console.Write("{0}\t", Array_3[i, j]);
                }
            }
            Console.ReadLine();
        }
    }

Output:
Enter size of matrix - 2

Enter values for matrix 1
First Matrix element - [0,0]:1
First Matrix element - [0,1]:2
First Matrix element - [1,0]:3
First Matrix element - [1,1]:4

Second Matrix element - [0,0]:1
Second Matrix element - [0,1]:2
Second Matrix element - [1,0]:3
Second Matrix element - [1,1]:4


Values inserted in Matrix 1

1       2
3       4

Values inserted in Matrix 2

1       2
3       4

Sum of Two Matrix

2       4
6       8

Read 2D Array of size 3*3 and print the matrix

Hello,This is simple program to know use of multidimensional array.please go through it. I will update more programs on this on next blog.

Thank you.


 class Program
    {
        static void Main(string[] args)
        {
            int[,]Two_Dim = new int[3,3];
            int i, j;
            for(i = 0; i < 3; i++)
            {
                for(j = 0; j < 3; j++)
                {
                    Console.Write("element - [{0},{1}]:", i, j);
                    Two_Dim[i,j] = Convert.ToInt32(Console.ReadLine());
                }
            }
            for (i = 0; i < 3; i++)
            {
                Console.WriteLine("");
                for (j = 0; j < 3; j++)
                {
                    Console.Write("{0}\t", Two_Dim[i, j]);
                }
            }
            Console.ReadLine();
        }
    }


 Output:
element - [0,0]:1
element - [0,1]:2
element - [0,2]:3
element - [1,0]:4
element - [1,1]:5
element - [1,2]:6
element - [2,0]:7
element - [2,1]:8
element - [2,2]:9

1       2       3
4       5       6
7       8       9

Program for merged two arrays and display it in ascending order

Hi,This program is for merging two arrays and display those values in order.
Hope it will helpful for you.

class Program
    {
        static void Main(string[] args)
        {
            int[] array_one = new int[] { };
            int[] array_two = new int[] { };
            int[] merged_array = new int[] { };
           
            int i, j;
            int Array_One_Total, Array_Two_Total;
            Console.Write("Enter total no of element for array_one:-");
            Array_One_Total = Convert.ToInt32(Console.ReadLine());
            array_one = new int[Array_One_Total];
            //Insert into first array
            for (i = 0; i <= array_one.Length - 1; i++)
            {
                Console.Write("Array one element {0} - ", i);
                array_one[i] = Convert.ToInt32(Console.ReadLine());
            }
            Console.WriteLine("-----------");
            Console.Write("Enter total no pf element for array_two:-");
            Array_Two_Total = Convert.ToInt32(Console.ReadLine());
            array_two = new int[Array_Two_Total];
            //Insert into second array
            for (j = 0; j <= array_two.Length - 1; j++)
            {
                Console.Write("Array two element {0} - ", j);
                array_two[j] = Convert.ToInt32(Console.ReadLine());
            }
            i = 0; j = 0;
            //Declare merged array
            merged_array = new int[Array_One_Total + Array_Two_Total];
            //Set values in merged array

          
            for (i = 0; i < array_one.Count(); i++)
            {
                merged_array[i] = array_one[i];
            }
            for (j = 0; j < array_two.Count(); j++)
            {
                merged_array[i] = array_two[j];
                i++;
            }
           
            //Display merged array
            Console.WriteLine("Merged array");
            Array.Sort(merged_array); //Sort array to display it in ascending order
            for (int k = 0; k < merged_array.Length; k++)
            {
                Console.WriteLine("{0}", merged_array[k]);
            }
            Console.ReadLine();
        }
    }

   For ex input: Enter total no of element for array_one:-3
Array one element 0 - 3
Array one element 1 - 2
Array one element 2 - 1
-----------
Enter total no pf element for array_two:-3
Array two element 0 - 6
Array two element 1 - 5
Array two element 2 - 4

Output:
Merged array
1
2
3
4
5
6

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...