Ref and Out

What is Ref and Out Keyword?

Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.


Please find below example for more clarity.I have used both ref and out parameter and also describe how it's work. you can also find different between ref and out comparing codes.


  class Proram
    {
        public static void Main() //Calling Method
        {
            int refval=0;//Must be define value
            int outval; //No need to define value

            GetNumberByRef(ref refval);
            Console.WriteLine("Values after called method using ref is {0} ", refval);

            GetNumberByOut(out outval);
            Console.WriteLine("Value after called method using our is {0} ", outval);

            Console.ReadLine();
        }
        public static void GetNumberByRef(ref int value)//Called Method
        {
            value = 101;//here it's optional to define value
        }
        public static void GetNumberByOut(out int value)//Called Mathod
        {
            value = 101;//You must define value here
           
        }
    }

Output
 
Values after called method using ref  is 101
Value after called method using our is  101


Note: Out and ref cannot be used in method with async mathod.

Async await in c#

What is async await in c#?


You might have already heard about asynchronous programming, either in C# or in some other language. In this page I will try to explain it to you, how to understand the concept easily, why and when we write asynchronous, the structure of async / await.

Asynchronous programming is very helpful in this condition. By using Asynchronous programming, the Application can continue with the other work that does not depend on the completion of the whole task.if any task depends on another task then next task will not execute until first task not completed.

Async and await are the code markers, which marks code positions from where the control should resume after a task completes.

We will get all the benefits of traditional Asynchronous programming with much less effort by the help of async and await keywords.

Let's take example so understand it properly

class Proram
    {
        public static void Main()
        {
       
            ProcessOne();
            IndependentProcess();//this process will run separately
            Console.ReadLine();
        }
        public async static void ProcessOne()
        {
            /*
             You can see that we mark DependedProcess method as await
             means untill DependedProcess will not complete next line will not called
            */
            await Task.Run(new Action(DependedProcess));
            Console.WriteLine("Process One Called");
        }
     
        public static void DependedProcess()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Process Two Called");
        }
        public static void IndependentProcess()
        {
            Console.WriteLine("Independent Process");
        }
    }

Output:
Independent Process
Process Two Called
Process One Called

Summary: In above program you can see that Once DependentProcess method complete process after that next line of code will execute.while Independentprocess method will run separately this is called the Asynchronous programming.



















Operator Overloading

What is Operator overloading?

Opearator overloading is a concept which is related to polymorphisam. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.

Operator overloading gives the ability to use the same operator to do various operations

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list.

Let's try to understand  Operator overloading (+)  by below example. using the + Operator you can do addition of two values and also contact two strings as below

 Obj 1 Operator     Obj 2 Result
 "C#"+ "Tutorial" C# Tutorial  
 15   +     20 35
Obj1       +    Obj2  can we do like that?? (let's do that with Operator Overloading) 


Please see below example for operator overloading and get to know that how we do addition of Obj1 + Obj2. run it on your machine to get more clerify.

    class Proram
    {
        public static void Main()
        {
            Course obj1 = new Course();
            obj1.Name = "C#";
            obj1.TotalMarks = 200;

            Course obj2 = new Course();
            obj2.Name = "Programming";
            obj2.TotalMarks = 300;

            Course obj3 = new Course();
            obj3 = obj1 + obj2;//Here operator overloading called.

            Console.WriteLine(obj3.Name + " - " + obj3.TotalMarks);
            Console.ReadLine();
        }
    }
    class Course
    {
        public string Name = "";
        public int TotalMarks = 0;

        public static Course operator +(Course Obj1, Course Obj2)
        {
            Course Obj3 = new Course();
            Obj3.Name = Obj1.Name + Obj2.Name;
            Obj3.TotalMarks = Obj1.TotalMarks + Obj2.TotalMarks;
            return Obj3;
        }
    }

Output
C#Programming - 500




Please visit given link for more details on Operator overloadig 

Sorted List - Generic

C# Sorted List

In c#, SortedList is a generic type of collection and it is used to store a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

By default, the sortedlist will sort a key/value pairs in ascending order of the key and the sortedlist will allow storing only the strongly-typed objects i.e. the key/value pairs of the specified data type.

In c#, the sortedlist will allow us to store duplicate values but the keys must be unique and cannot be null to identify the values in sortedlist and the size of sortedlist will vary dynamically so you can add or remove elements from the sortedlist based on our application requirements.

C# includes two type of SortedList, generic SortedList and non-generic SortedList. Generic SortedList denotes with angel bracket: SortedList<TKey,TValue> where TKey is for type of key and TValue is for type of value. Non-generic type do not specify the type of key and values.


You can instantiate SortedList<TKey, TValue> by specifying type for key and value, as shown below.

Ex. SortedList<TKey, TValue> slist = new SortedList<TKey, TValue>();


Properties


 Property     Description
 Capacity     Gets or sets the number of elements that the SortedList<TKey,TValue> can store 
 Count Gets the total number of elements exists in the SortedList<TKey,TValue>.
 IsReadOnly Returns a boolean indicating whether the SortedList<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the SortedList<TKey,TValue>.
 Keys Get list of keys of SortedList<TKey,TValue>
 Values Get list of values in SortedList<TKey,TValue>.


Method

 Method         Description
Add  Add key-value pairs into SortedList<TKey, TValue>.
Remove Removes element with the specified key.
Remove At Removes element at the specified index.
Contains Key Checks whether the specified key exists in SortedList<TKey, TValue>.
Contains Value Checks whether the specified key exists in SortedList<TKey, TValue>.
Clear Removes all the elements from SortedList<TKey, TValue>.
Index Of Key Returns an index of specified key stored in internal array of SortedList<TKey, TValue>
Index Of Value
 Returns an index of specified value stored in internal array of SortedList<TKey,   TValue>
Try Get Value Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 class CollectionExamples
    {
        public static void Main(String[] args)
        {

            SortedList<int, string> sl = new SortedList<int, string>();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            foreach (var item in sl.Keys)
            {
                Console.WriteLine("Sorted List {0}", item);
            }
            Console.ReadLine();

        }
    }


Dictionary

C# Dictionary


  • The Dictionary<TKey, TValue> class is a generic collection class in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of TValue.
  • There is a non-generic collection called a Hashtable, which does the same thing, except that it operates on type object. However, you want to avoid the non-generic collections and use their generic counterparts instead
  • Dictionary cannot include duplicate or null keys, where as values can be duplicated or set as null. Keys must be unique otherwise it will throw a runtime exception.
  • The capacity of a Dictionary is the number of elements that Dictionary can hold.


Properties

 Property

 Description

 Count             Gets the total number of elements exists in the Dictionary<TKey,TValue>              .
 IsReadOnly Returns a boolean indicating whether the Dictionary<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the Dictionary<TKey,TValue>.
 Keys Returns collection of keys of Dictionary<TKey,TValue>.
 Values Returns collection of values in Dictionary<TKey,TValue>.

Methods


 Method     Description
 Add                Add key-value pairs in Dictionary<TKey, TValue> collection.                                                                  
 Remove     Removes the first occurrence of specified item from the Dictionary<TKey, TValue>.
 ContainsKey  Checks whether the specified key exists in Dictionary<TKey, TValue>.
 ContainsValue Checks whether the specified key exists in Dictionary<TKey, TValue>.
 Clear Removes all the elements from Dictionary<TKey, TValue>.
 TryGetValue Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 public static void Main(String[] args)
   {
           
            Dictionary<int, string> _dictionary =  new Dictionary<int, string>();

            // Adding key/value pairs  
            _dictionary.Add(1, "Hello");
            _dictionary.Add(2, "This is");
            _dictionary.Add(3, "Blog for C#");

            _dictionary.Remove(1); //Remove value which key is 1

            Console.WriteLine("Is Key Exist?: {0}",_dictionary.ContainsKey(2));//Return True
            Console.WriteLine("Is Value Exist?: {0}", _dictionary.ContainsValue("This is"));//Return True
            foreach (KeyValuePair<int, string> ele1 in _dictionary)
            {
                Console.WriteLine("{0} and {1}",
                          ele1.Key, ele1.Value);
            }
            Console.ReadLine();

           
    }

List

 What is C# List<T>

  • List<T> class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace
  • List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists.
  • It is different from the arrays. A List<T> can be resized dynamically but arrays cannot.
  • List<T> class can accept null as a valid value for reference types and it also allows duplicate elements.
  • If the Count becomes equals to Capacity, then the capacity of the List increased automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
  • List<T> class is the generic equivalent of ArrayList class by implementing the IList<T> generic interface.
  • This class can use both equality and ordering comparer.
  • List<T> class is not sorted by default and elements are accessed by zero-based index.
  • For very large List<T> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

Properties


 
Properties            
 Description 
 Capacity     Gets or sets the total number of elements the internal data structure can hold without resizing.
 Count Returns the total number of elements exists in the List<T>    
 Item Gets or sets the element at the specified index.


Methods


 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 speciied 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>.
 Remove<T>     Removes the first occurrence of a specific object from the List<T>.
 Remove All<T>            Removes all the elements that match the conditions defined by the specified predicate.
 Remove At(Int32) Removes the element at the specified index of the List<T>.
 RemoveRange(Int32,Int32)  Removes a range of elements from the List<T>.
 Reverse() Reverses the order of the elements in the List<T> or a portion of it.
 Sort()Sorts the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.    
 ToArray() Copies the elements of the List<T> to a new array.


Example:

class CollectionExamples
    {
        public static void Main(String[] args)
        {

            // Creating an List<T> of Integers 
            List<int> _List = new List<int>();

            // Adding elements to List 
            _List.Add(1);
            _List.Add(3);
            _List.Add(4);
            _List.Add(7);
            _List.Add(9);
            _List.Add(18);
            _List.Add(22);

            Console.WriteLine("Elements Present in List:\n");

            int p = 0;

            // Displaying the elements of List 
            foreach (int k in _List)
            {
                Console.Write("At Position {0}: ", p);
                Console.WriteLine(k);
                p++;
            }

            Console.WriteLine(" ");

            // removing the element at index 3 
            Console.WriteLine("Removing the element at index 3\n");
            _List.RemoveAt(4);

            int p1 = 0;

            // Displaying the elements of List 
            foreach (int n in _List)
            {
                Console.Write("At Position {0}: ", p1);
                Console.WriteLine(n);
                p1++;
            }
        }

Queue(Non Generic)

Queue:

C# includes a Queue collection class in the System.Collection namespace. Queue stores the elements in FIFO style (First In First Out), exactly opposite of the Stack collection. It contains the elements in the order they were added.

Queue collection allows multiple null and duplicate values.

Use the Enqueue() method to add elements into Queue

The Dequeue() method returns and removes elements from the beginning of the Queue. Calling the Dequeue() method on an empty queue will throw an exception.

The Peek() method always returns top most element.


Properties of queue

Count - Returns the total count of elements in the Queue.

Methods of queue

  1. Enqueue: Adds an item into the queue.
  2. Dequeue: Removes and returns an item from the beginning of the queue.
  3. Peek: Returns an first item from the queue
  4. Contains: Checks whether an item is in the queue or not
  5. Clear: Removes all the items from the queue.
  6. TrimToSize: Sets the capacity of the queue to the actual number of items in the queue.



1.Enqueue: Enqueue method is used to add element in queue.you can add element of any datatype as it's a non-generic collection.

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null

            foreach(var item in _queue)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadLine();
        }
    }

2.Dequeue: 
Dequeue() method is used to retrieve the top most element in a queue collection.

Dequeue() removes and returns a first element from a queue because the queue stores elements in FIFO order.
 
Calling Dequeue() method on empty queue will throw InvalidOperation exception. So always check that the total count of a queue is greater than zero before calling the Dequeue() method on a queue.

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null


           Console.WriteLine("Length Before Dequeue {0}", _queue.Count);
           Console.WriteLine("Calling Dequeue {0}", _queue.Dequeue()); //Return first element and remove it.
           Console.WriteLine("Length After Dequeue {0}", _queue.Count);

            Console.ReadLine();
        }
    }

Output:

Length Before Dequeue 5
Calling Dequeue 1
Length After Dequeue 4


3. Peek() : The Peek() method always returns the first item from a queue collection without removing it from the queue. 

Calling Peek() and Dequeue() methods on an empty queue collection will throw a run time exception "InvalidOperationException".

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null


           Console.WriteLine("Length Before Dequeue {0}", _queue.Count);
           Console.WriteLine("Calling Dequeue {0}", _queue.Peek()); //Return first element
           Console.WriteLine("Length After Dequeue {0}", _queue.Count);

            Console.ReadLine();
        }
    }

Output

Length Before Dequeue 5
Calling Dequeue 1
Length After Dequeue 5


4.Contains()
The Contains() method checks whether an item exists in a queue. It returns true if the specified item exists; otherwise it returns false.

Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null


           Console.WriteLine(_queue.Contains(1)); // it will return true
        

            Console.ReadLine();
        }
    }


5.Clear() :The Clear() method removes all the items from a queue.

Example

 static void Main(string[] args)
        {
            Queue _queue = new Queue();
            _queue.Enqueue(1);
            _queue.Enqueue(2);
            _queue.Enqueue(3);
            _queue.Enqueue(3); //it allows duplicate
            _queue.Enqueue(null); // it allows null

            _queue.Clear();
           Console.WriteLine(_queue.Count);//it will return 0
        

            Console.ReadLine();
        }

Stack(Non generic)

C# Stack

C# includes a special type of collection which stores elements in LIFO style (Last In First Out).

Stack allows null value and also duplicate values. It provides a Push() method to add a value and Pop() or Peek() methods to retrieve values.

Use the Push() method to add elements into Stack.

The Pop() method returns and removes elements from the top of the Stack. Calling the Pop() method on the empty Stack will throw an exception.

The Peek() method always returns top most element in the Stack.

Properties

Count- Return the total count of element in the stack.

Method

  1. Push: Inserts an item at the top of the stack.
  2. Peek: Returns the top item from the stack.
  3. Pop: Removes and returns items from the top of the stack.
  4. Contains: Checks whether an item exists in the stack or not.
  5. Clear: Removes all items from the stack.

1. Push: The Push() method adds values into the Stack. It allows value of any datatype

Example:

  static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);

            foreach (var item in _stack)
            Console.WriteLine(item);
            Console.ReadLine();

        }

2.Peek: The Peek() method returns the last (top-most) value from the stack. Calling Peek() method on empty stack will throw InvalidOperationException. So always check for elements in the stack before retrieving elements using the Peek() method.

The below program return 4 as an output.

Example
class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);
            Console.WriteLine(_stack.Peek());
            Console.ReadLine();

        }
    }

3.Pop(): You can also retrieve the value using the Pop() method. The Pop() method removes and returns the value that was added last to the Stack. The Pop() method call on an empty stack will raise an InvalidOperationException. So always check for number of elements in stack must be greater than 0 before calling Pop() method.

Below program retrurn 3,2 and  1 as an output.
Example

 class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);
            _stack.Pop();
            foreach (var item in _stack)
                Console.WriteLine("items {0}", item);
            Console.ReadLine();

        }
    }
    
4.Contains():The Contains() method checks whether the specified item exists in a Stack collection or not. It returns true if it exists; otherwise it returns false.

Below program return true as an output.

class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);
            Console.WriteLine("Is Exist : {0}", _stack.Contains(1));
            Console.ReadLine();
        }
    }


5.Clear() :The Clear() method removes all the values from the stack.

class CollectionExamples
    {
        static void Main(string[] args)
        {
            Stack _stack = new Stack();
            _stack.Push(1);
            _stack.Push(2);
            _stack.Push(3);
            _stack.Push(4);

           _stack.clear();
            Console.WriteLine("Total {0}",_stack.count);
            Console.ReadLine();
        }

Sorted List(Non generic)

C# Sorted List(Non generic)


In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order.
Non-generic SortedList is defined under System.Collections namespace

Properties of Sorted List

  1. Capacity: Gets or sets the number of elements that the SortedList instance can store.
  2. Count: Gets the number of elements actually contained in the SortedList.
  3. IsFixedSize: Gets a value indicating whether the SortedList has a fixed size.
  4. IsReadOnly: Gets a value indicating whether the SortedList is read-only.
  5. Item : Gets or sets the element at the specified key in the SortedList.
  6. Keys: Get list of keys of SortedList.
  7. Values: Get list of values in SortedList.


Method of Sorted List

1) Add(object key, object value): Add key-value pairs into SortedList.
Key cannot be null but value can be null. Also, datatype of all keys must be same, so that it can compare otherwise it will throw runtime exception.

Non-generic SortedList collection can contain key and value of any data type. So values must be cast to the appropriate data type otherwise it will give compile-time error.

Example:

class CollectionExamples
    {
        static void Main(string[] args)
        {

            SortedList sl = new SortedList();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            foreach (var item in sl.Keys)
            {
                Console.WriteLine("Sorted List {0}", item);
            }
            Console.ReadLine();

        }
    }

Output:
Sorted List 1
Sorted List 2
Sorted List 3
Sorted List 4

2) Remove(object key): Removes element with the specified key.
3) RemoveAt(int index): Removes element at the specified index.

Example

 static void Main(string[] args)
        {

            SortedList sl = new SortedList();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            sl.Remove(3);//Remove element whose key is two
            sl.RemoveAt(0);//Remove element whose index is 1
            foreach (DictionaryEntry de in sl)
            {
                Console.WriteLine("Sorted List {0}", de.Key);
            }
            Console.ReadLine();

        }

Output:

Sorted List 2
Sorted List 4


4)Contains: This method is used to check whether a SortedList object contains a specific key.
5)ContainsKey: This method is used to check whether a SortedList object contains a specific key.
6)ContainsValue: This method is used to check whether a SortedList object contains a specific value.

Example:

        static void Main(string[] args)
        {

            SortedList sl = new SortedList();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            Console.WriteLine("Contains {0}",sl.Contains(3)); // Return true if given key is found.
            Console.WriteLine("Contains Key {0}", sl.ContainsKey(3));// Return true if given key is found.
            Console.WriteLine("Contains value {0}", sl.ContainsValue("Three"));//Return true if given value found.
            
            Console.ReadLine();

        }


GetByIndex(int index) Returns the value by index stored in internal array
GetKey(int index): Returns the key stored at specified index in internal array
IndexOfKey(object key): Returns an index of specified key stored in internal array
IndexOfValue(object value) Returns an index of specified value stored in internal array


Note:Internally, SortedList maintains two object[] array, one for keys and another for values. So when you add key-value pair, it runs a binary search using the key to find an appropriate index to store a key and value in respective arrays. It re-arranges the elements when you remove the elements from it.


HashTable in C#


What is HashTable?


C# includes Hashtable collection in System.Collections namespace, which is similar to generic collection. The Hashtable collection stores key-value pairs. It optimizes lockups by computing the hash code of each key and stores it in a different bucket internally and then matches the hash code of the specified key at the time of accessing values.

Properties of Hashtable

Count: Gets the total count of key/value pairs in the Hashtable.
IsReadOnly: Gets boolean value indicating whether the Hashtable is read-only.
Item :Gets or sets the value associated with the specified key.
Keys :Gets an ICollection of keys in the Hashtable.
Values : Gets an ICollection of values in the Hashtable

Methods of HashTable

Add : The Add() method adds an item with a key and value into the Hashtable. Key and value can be of any data type. Key cannot be null whereas value can be null.

Example
static void Main(string[] args)
         {

            Hashtable ht = new Hashtable();
            ht.Add(1, "One");
            ht.Add(2, 2);
            ht.Add(3, 3.0);
            ht.Add(4, null);
        }

Remove: Removes the item with the specified key from the hashtable.

Example
static void Main(string[] args)
         {

            Hashtable ht = new Hashtable();
            ht.Add(1, "One");
            ht.Add(2, 2);
            ht.Add(3, 3.0);
            ht.Add(4, null);

            ht.Remove(1);
        }

Clear: Removes all the items from the hashtable.
Example

 static void Main(string[] args)
         {

            Hashtable ht = new Hashtable();
            ht.Add(1, "One");
            ht.Add(2, 2);
            ht.Add(3, 3.0);
            ht.Add(4, null);

            ht.Clear();
        }


Contains: Checks whether the hashtable contains a specific key.
Example

 static void Main(string[] args)
         {

            Hashtable ht = new Hashtable();
            ht.Add(1, "One");
            ht.Add(2, 2);
            ht.Add(3, 3.0);
            ht.Add(4, null);

            ht.Contains(1);//return true;
            ht.Contains(1);//return true;
            ht.Contains(5); //return false
        }

ContainsKey: Checks whether the hashtable contains a specific key it work similar as Contains.

ContainsValue: Checks whether the hashtable contains a specific value.

 static void Main(string[] args)
         {

            Hashtable ht = new Hashtable();
            ht.Add(1, "One");
            ht.Add(2, 2);
            ht.Add(3, 3.0);
            ht.Add(4, null);
            ht.ContainsValue(5); //return true
        }

GetHash: Returns the hash code for the specified key.




Summary:

  • Hashtable stores key-value pairs of any datatype where the Key must be unique.
  • The Hashtable key cannot be null whereas the value can be null.
  • Hashtable retrieves an item by comparing the hashcode of keys. So it is slower in performance than Dictionary collection.
  • Hashtable uses the default hashcode provider which is object.GetHashCode(). You can also use a custom hashcode provider.
  • Use DictionaryEntry with foreach statement to iterate Hashtable.


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