A Developer Journey who codes for fun

Daily Dose Of Code

  • Home
  • Dot.Net Basics
    • .Net Basics
      • CTS
      • CLS
      • CLR
      • Strong Vs Weak Ref
      • .Net Framework
      • What is Manifest
    • Memory Management
      • Garbage Collection 1
      • Garbage Collection 2
      • Circular Reference
  • C Sharp
    • Abstract Class in C#
    • Interfaces in C#
    • Value type by Val and By Ref
    • Var keyword
    • Null Coalescing Operator
    • Buit-in code snippets
  • OOPS
    • Abstraction and Encapsulation
    • Polymorphism
    • Inheritence
    • Aggregation
  • Threading
    • Delegates
      • Calling Delegate using Invoke, BeginInvoke
      • Multicast Delegate
      • Exception Handling in Multicast Delegate
      • Action
      • Predicate
      • Func
    • Synchronization
    • Thread Pool
    • Exception Handling
    • TPL
  • Design Pattern
    • Creational Patterns
      • Singleton Pattern
      • Factory Pattern
      • Abstract Factory Pattern
      • Prototype Pattern
      • Builder Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Proxy Pattern
      • Facade Pattern
      • Decorator Pattern
      • Flyweight Pattern
    • Behavioral Patterns
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
      • Visitor Pattern
      • Chain Of Responsibility Pattern
      • Template Pattern
  • Data Structures
    • Generic List in C#
    • 2d array to 1d array
    • 3d arrayto 1d array
    • Linked List
      • Singly Linked List in C#
    • Queue
      • Dummy Data 1
    • Stack
      • Dummy Data 2
    • Tree
      • Dummy Data 3
    • Graph
      • Dummy Data 4
  • WCF
    • WCF Service using VS 2015
  • Scripts
    • Chrome Extensions
      • Create a Chrome Extension
      • Facebook autologout script
      • Gmail autologout script

Singly Linked List in C#

 Unknown     1:50 AM     Data Structures, Linked List     No comments   

Node class is a generic class that will help to initialize each node of linked list.
 
public class Node
{
    public Node(T value)
    {
        this.Value = value;
    }

    public T Value { get; set; }

    public Node Next { get; set; }

    public override string ToString()
    {
        return this.Value.ToString();
    }
}

    /// <summary>
    /// This is a singly linked list and it will allow you to add bunch of Node<T>s
    /// and that will be linked to each other.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class LinkedList where T : IEnumerable
    {
        public LinkedList(IEnumerable collection)
        {
            if (collection == null)
            {
                throw new NullReferenceException("collection is null");
            }
            foreach (T item in collection)
            {
                this.Add(item);
            }
        }

        public int Count { get; set; }

        private Node firstNode;

        public Node FirstNode
        {
            get { return firstNode; }
            private set { firstNode = value; }
        }

        private Node lastNode;

        public Node LastNode
        {
            get { return lastNode; }
            private set { lastNode = value; }
        }


        public void AddFirst(T item)
        {
            Node newNode = new Node(item);
            if (this.FirstNode == null)
            {
                this.FirstNode = this.LastNode = newNode;
            }
            else
            {
                newNode.Next = this.FirstNode;
                this.FirstNode = newNode;
            } this.Count++;
        }

        /// <summary>
        /// Add will always add the items at last.
        /// </summary>
        /// <param name="item"></param>
        public void Add(T item)
        {
            Node newNode = new Nodeitem);
            if (this.LastNode == null)
            {
                this.FirstNode = this.LastNode = newNode;
            }
            else
            {
                this.LastNode.Next = newNode;
                this.LastNode = newNode;
            }
            this.Count++;
        }

        /// <summary>
        ///  Add new item after particular Node<T>
        /// </summary>
        /// <param name="node"></param>
        /// <param name="item"></param>
        public void AddAfter(Node node, T item)
        {
            if (node == null)
            {
                return;
            }
            Node; newNode = new Nodeitem);
            if (node.Next == null)
            {
                node.Next = newNode;
            }
            else
            {
                newNode.Next = node.Next;
                node.Next = newNode;
            }
            this.Count++;
        }

       /// <summary>
       /// Remove the item
       /// </summary>
       /// <param name="item"></param>
        public void Remove(T item)
        {
            if (item == null)
            {
                throw new NullReferenceException("item is null");
            }
            Node newNode = this.Find(item);
            this.RemoveTheRef(ref newNode);
        }

        /// <summary>
        /// Remove the first node
        /// </summary>
        public void RemoveFirst()
        {
            Node first = this.FirstNode;
            RemoveTheRef(ref first);
        }

        /// <summary>
        /// Remove the last node
        /// </summary>
        public void RemoveLast()
        {
            Node last = this.LastNode;
            RemoveTheRef(ref last);
        }

       /// <summary>
       /// Find the item inside list.
       /// </summary>
       /// <param name="value"></param>
       /// <returns></returns>
        public Node Find(T value)
        {
            Node Node = this.FirstNode;
            while (Node != null)
            {
                if (Node.Value.Equals(value))
                {
                    return Node;
                }
                Node = Node.Next;
            }
            return null;
        }

        ///          
        /// Find previous Node<T>
        /// 
        public Node FindPreviousNode(T value)
        {
            Node Node = this.FirstNode;
            Node previousNode = this.FirstNode;
            while (Node != null)
            {
                if (Node.Value.Equals(value))
                {
                    return previousNode;
                }
                previousNode = Node;
                Node = Node.Next;
            }
            return null;
        }

        /// <summary>
        /// Clear the collection
        /// </summary>
        public void Clear()
        {
            this.FirstNode = null;
            this.LastNode = null;
            this.Count = 0;
        }

        /// <summary>
        /// Get enumerator will help you to traverse the collection
        /// </summary>
        /// <returns></returns>
        IEnumerator GetEnumerator()
        {
            Node currentNode = this.FirstNode;
            while (currentNode != null)
            {
                yield return currentNode.Value;
                currentNode = currentNode.Next;
            }
        }

        ///                 
        /// Remove the item from the linked list.  
        /// 
        public void RemoveTheRef(ref Node<T> Node)
        {
            if (Node != null)
            {
                Node prevNode = FindPreviousNode(Node.Value);
                if (prevNode != null)
                {
                    prevNode.Next = Node.Next;
                }
                if (Node.Equals(this.FirstNode))
                {
                    this.FirstNode = Node.Next;
                }
                if (Node.Equals(this.LastNode))
                {
                    this.LastNode = prevNode;
                }
            }
            Node = null;
            this.Count--;
        }
    }
 
Guys, there is some problem in posting generic type. So please Replace Node to Node of T type
 
Happy Coding :)

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Abstract Class

 Unknown     10:54 PM     C#     No comments   


Abstract classes are the base class of C#. Looks good but What is abstract keyword?

So abstract is a modifier that can be used with classes, indexers, properties, methods and events.
Let's talk about Abstract Class first -

abstract class BaseClass
{

}

Using abstract keyword we can  create abstract class. These classes are always implemented in inheritance model. Some points need to remember before implementing it -

1.  Abstract classes cannot be instantiated.

2.  Abstract class may or may not contain abstract methods.

3.  Abstract classes can inherit interfaces and that class should implement all interface members.

4.  Abstract class can have public, protected constructor but still you cannot instantiate it.

5.  Abstract class can inherit Abstract class but need not to implement/override any abstract method .

6.  Child class must override all abstract methods but may override virtual methods.

7.  Abstract methods cannot mark as virtual.

8.  You cannot use private access modifier in case of abstract/virtual methods.

Point 1 - Abstract classes cannot be instantiated.

See this -



An Abstract keyword is define in a way you can create only subtype of that. This is how framework designed abstract keyword. But if I say you can create an instance of abstract class. Confused ??
 
public MainClass()
{
    BaseClass obj = new ChildClass();
}

Yes Base class can be instantiated through child class only.

Point 2 - Abstract classes may or may not contain abstract methods.

As code mentioned in above example my abstract class doesn't have any abstract method. I do not get any compile time error for the same.


Point 3 - Abstract classes may can inherit interfaces and that class should implement all interface members




















So if you do not implement interface members in abstract class it will give you a compile time error. 
 
Point 4 - Abstract class can have public, protected or private constructor but still you cannot instantiate it.

public abstract class BaseClass
{
        public BaseClass()
        {

        }

        private BaseClass(string name)
        { 
        
        }

        protected BaseClass(string name, string instantiatedFor)
        { 
            
        }

        void MYMethod()
        { 
            
        }
 }

After defining these constructors you still cannot instantiate it by default. 
So what is the use case of defining these constructors in the abstract class ?
Child classes can pass some data to base class to initialize it. Let's say child classes want to initialize base
class with their name to track the object.

 
 
 
 
 
 
 
 
 
 
 
 
 
 



Point 5 - Abstract class can inherit Abstract class.

Yes Abstract class can inherit abstract class but they need not to override any method defined in super base class. See below image for more understanding.



















Point 6 - Child classes must override all abstract methods but may override virtual methods.

See the below example for more understanding -

public abstract class BaseClass1
{
    public abstract void MyMethod();
}

public abstract class BaseClass2 : BaseClass1
{
    public virtual void MyMethod2()
    { 
      //some base implementation.
    }
}

public class ChildCLass : BaseClass2
{ 
    
}


So in case you have some base implementation and you do not want to override it in child class then mark it as virtual so marking it virtual you are explaining to CLI. You may or may not override this method. So to fix this error -

public class ChildCLass : BaseClass2
{
     public override void MyMethod()
     {
           //Some implementation
     }
}

Point 7 - Abstract methods cannot mark as virtual.

See the compile time error for more understanding














Point 8 - You cannot use private access modifier in case of abstract/virtual methods.
 
See below screenshot for more understanding -






















Hope you enjoyed reading this article. Drop a comment if you still have some confusion.

Happy Coding :)


 
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Singleton Pattern in C Sharp

 Unknown     5:25 AM     Design Patterns     1 comment   

Few points before choosing Singleton Pattern
  • Instance will be available till Appdomain exist.
  • You can not allow any parameters while creating instance of a singleton class
If .NET target version is less than 4.0 then this is the right way of implementing Singleton Pattern


public sealed class MySingleton
    {
        private MySingleton()
        {
        }

        public static MySingleton Instance { get { return Nested.instance; } }

        class Nested
        {
            internal static readonly MySingleton instance = new MySingleton();
        }
    }


 
But here is the twist if we create a static field initializer then the class can be marked as beforefieldinit and this will invoke the type initializer at any time before the first reference to any member


class Nested  
     {  
       // Explicit static constructor to tell C# compiler  
       // not to mark type as beforefieldinit  
       static Nested()  
       {  
       }  
       internal static readonly Singleton instance = new Singleton();  
     }  


So when we define a static constructor it means it can be accessed only any one of the member get referenced or instance is initialized of the class.

In case .NET Framework is greater than 4.0 then -

public sealed class SingletonUsingLazy
    {
        private static readonly Lazy<SingletonUsingLazy> lazy =
                new Lazy<SingletonUsingLazy>(() => new SingletonUsingLazy());

        private SingletonUsingLazy() { }

        public static SingletonUsingLazy Instance
        {
            get
            {
                return lazy.Value;
            }
        } 
    }



Thanks to Jon Skeet for writing this amazing article- Singleton Pattern
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Implement your own Generic list in C#

 Unknown     11:19 AM     Data Structures     6 comments   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace MyGenericList
{
    public class MyGenericList where T : IComparable
    {
        const int defaultCapacity = 6;
 
        private T[] list = null;
 
        public MyGenericList(int capacity = defaultCapacity)
        {
            this.Count = 0;
            this.Capacity = capacity;
            list = new T[capacity];
        }
 
        private int capacity;
 
        public int Capacity
        {
            get { return capacity; }
            private set { capacity = value; }
        }
 
        private int count;
 
        public int Count
        {
            get { return count; }
            set { count = value; }
        }
 
        public void Add(T item)
        {
            this.Count++;
            this.Resize(this.Count);
            list[count - 1] = item;
        }
 
        public void RemoveAt(int index)
        {
            if (index &gt; Count || index &lt; 0)
            {
                throw new IndexOutOfRangeException("Index is out of range.");
            }
 
            this.Count--;
            this.Resize(this.Count);
            Array.Copy(this.list, index, this.list, index--, this.Count - index);
            this.list[count] = default(T);
        }
 
        public void Insert(int index, T element)
        {
            if (index &gt; Count || index &lt; 0)
            {
                throw new IndexOutOfRangeException("Index is out of range.");
            }
 
            this.Count++;
            this.Resize(this.Count);
            Array.Copy(this.list, index, this.list, index++, this.Count - index -1);
            this.list[index - 1] = element;
 
        }
 
        public int FindIndex(T item)
        {
            return Array.IndexOf(this.list, item);
        }
 
        public bool Contains(T item)
        {
            return this.list.Contains(item);
        }
 
        public void Clear()
        {
            this.Count = 0;
            this.Capacity = defaultCapacity;
            this.list = new T[Capacity];
        }
 
        private void Resize(int currentCounter)
        {
            if (currentCounter &gt; this.Capacity)
            {
                this.Capacity = this.Capacity * 2;
                Array.Resize(ref this.list, this.Capacity);
            }
        }
    }
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Pass Value type parameters by value and by reference

 Unknown     6:32 AM     C#     1 comment   

We can pass value type parameters by two types -
  • Pass value type by value
  • Pass value type by reference
Pass value type parameter by value - Passing a value type variable to a method means passing a copy of a variable to the method and any changes occurs to that parameter will not reflect to the original copy, that's understandable but what about memory ?
All value type goes to stack so when you pass a parameter to another method as value type. It allocates a new memory location on stack. Let's see blow example -

















Memory allocation on value type parameters -













So the only problem is passing value type parameter is if we have to pass large value type so it will need memory(allocate new memory space) and will be expensive as well while copying data every time. It will be inefficient if we will call this method multiple times. So to avoid this we can pass the value type as reference and this will just pass a pointer to that value.

Pass value type parameter by Reference- We can pass value type parameter as reference by using ref keyword. The original value of the parameter will be changed after calling the method.


















So this will change the original value of x and will print 7 and 7. This allocates memory efficiently and just create a pointer to the original address space. So whenever you try to fetch the value it will point to the original location - have a look on below screenshot -














Passing reference type as a parameter is almost same as passing value type as reference will discuss this in my next article.

Hope you enjoyed reading this article.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How does GC handles Circular References ?

 Unknown     12:27 AM     .Net Architechture     No comments   

This is very interesting question. Let me explain you Obj A -> Obj B ( object A refers to object B ) , Obj B -> Obj C ( object B  refers to object c ) and Obj C -> Obj B( object C again refers to Object B). So this is circular dependency.
So now when object A goes out of scope GC will collect this as object B refers by object A so this will also be collected but this also refers by Object C.... Grrrrrr lot of confusion huh ?
How GC takes care of this ?

GC is so smart. It doesn't bother about references. GC traverse by application roots now u must be thinking what are the application roots ?

Application roots are the entry points for GC and they referenced objects( if they exist otherwise null). So here is the list of application roots:
  1. Static objects and static fields
  2. Global objects
  3. Reference on stack to method parameters
  4. Reference on stack to local objects
  5. Reference to objects that are in managed heap( CPU registers)
So using these roots GC starts its execution to the program and use its unique marking technique. It traverse from root to child and mark the objects those are not going to be collected. Let's say in between A goes out of scope so it means GC will not mark A. If object A is not marked then B and C will not be marked because A was the entry point. So doesn't matter whether there is circular reference or not next time when GC runs it will collect all these objects because there is no way around to reach those objects.

GC is a non deterministic process which runs only when it needs to run for a particular generation and collect those objects those are not marked.

Hope you enjoyed reading this article.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Strong Vs Weak References

 Unknown     12:41 PM     .Net Architechture     3 comments   

Strong Reference -  As long as if application refers to the object. GC will not collect those objects. Those objects we say are strong reference objects.

Weak Reference - Even though application refers to the object, GC may collect those object or may not be. Those objects are weak referenced objects.

Confused ? Let me explain in brief -

We all know GC is a non deterministic background process so we do not know when it will be called. So only weak referenced objects may reside in the memory for the long time or may not be. So it's up to us whether we want our weak references in memory or not. Lets look over the below examples -

Weak references are of two types -

Short Lived: Short weak references looses the reference when GC comes into the picture


Long Lived: Long weak references retained in the memory even GC comes and reclaims the memory. so it means it's not been collected even the Finalizer of the method is called.

How can we create Weak References ?

WeakReference objWeakReference = new WeakReference(null);

How we can achieve this long lived weak References ?

 WeakReference objWeakReference = new WeakReference(null, true);

So now you can easily see this if you want to create a long lived object then you need to set trackResurrection variable to true to stop tracking of a particular object.

So in this way you can create a weak reference. Lets understand this with one example -

So in the above code i am casting my weak reference to strong reference(as i know my strong references will not be collected by GC anyways) and checking whether it's null or not. If it is null or reclaims by GC then i am creating those strings again otherwise weak reference will fetch it from the memory.

You can also check whether your reference is alive or not.

objWeakReference.IsAlive; will return you bool whether the object is in memory or not.

Hope you enjoyed reading the article.

Happy Coding :)









Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

What is Common Type System ?

 Unknown     10:42 AM     .Net Architechture     No comments   

CTS - Common Type System as name suggest it define types. How types are defined, declared , used and managed by common Language Runtime.? The main part is it supports cross language type integration. Confused ? Let me give you a simple example.

In C# i will define my Integer variable as int and in VB.Net i will say Integer. So when i will try to see the IL code in ILDASM tool .net treats both variable as Int32. The way of writing an integer may be different in different languages in .Net but Machine instructions are same and this is possible just because of Common Type System.

So that was the basic definition and understanding of CTS. Lets look over the types supported by CTS in .Net -
  1. Class
  2. Structure
  3. Delegates
  4. Interface
  5. Enumerations
We all know about above types  will discuss this in my later articles

Type Definitions supported by CTS in .Net -
  1. Access Modifiers( Type accessibility ) - Public, Private, protected, Internal, Protected Internal
  2. Attributes - We can define our custom attributes and provide additional details
  3. Base Types - You can derive your class with Base class, not more than one
  4. Interfaces - You can implement multiple inheritance using Interface
Type Members supported by CTS in .Net - 
  1. Fields
  2. Properties
  3. Indexes
  4. Methods
  5. Events
  6. Constructors
We all know about the type members i have defined above will discuss in later articles. So these are important things CTS takes care of in .Net

Hope you enjoyed reading the article.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

What is Common Language Specification ?

 Unknown     10:14 AM     .Net Architechture     No comments   

CLS is more about rules of .Net and it's a subset of CTS(Common Type System). You must be thinking of CTS, don't worry will discuss in my next article.

So CLS, is a basic set of language rules needed by the applications. CLS ensures Interoperability on other .Net languages. So if i want my C# code can communicate with VB code then it should be CLS compliant. If i will voilate any of C# compliant rule my VB.Net code will not be able to communicate with my C# code.

Now you must be thinking how i can assure my code is CLS compliant. So you can write an attribute in your assembly - Assembly.cs file.

[assembly : CLSCompliant(true)]

So after that whenever you will be breaking any of the rule you will get a warning in your code and CLS Compliancy

If you are interested in reading the CLS rules then visit  here

So now you understand about CLS now i will discuss some code to see live example -  



So now if i try to access my non compliant code in other language, I will not be able to use that. So using those warnings i can see that whether my code is CLSCompliant or not.



Hope you enjoyed reading the article.Let me know if you have any queries.


Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Garbage Collection - Automatic Memory Management Part II

 Unknown     5:57 AM     .Net Architechture     No comments   

Welcome friends in the second article of Garbage Collection. Those who have missed the first one can visit here. So in this article i will talk more about Generations.

So In my last article i mentioned GC has 3 generations: Gen 0, Gen1 and Gen 2. If you want to know the max generations used by application write : System.GC.MaxGeneration.

Now question comes How Generations improves the performance ?

Managed heap is divided into generations so that it is possible to eliminate dead objects by visiting a particular generation. By that way GC doesn't need to traverse complete graph of Heap and that improve performance significantly.

Generation 0 : This is the youngest Generation and all newly created and short lived objects goes under this generation until they are large objects(80000 bytes and above). Large objects goes directly in Generation 2

Generation 1 : Objects that are not reclaimed in Gen 0 promote to Gen 1. This contains short lived objects and kind of buffer between short lived and long lived objects.

Generation 2 : This contains long live objects and objects that are not reclaimed in Gen 1 promote to Gen 2. Data that lives long time in the process like static data and objects that survived in Gen 2 GC remains in Generation 2.

More objects in Gen 0, the more your application is good in performance. In my next article i will be writing about Strong Vs Weak reference and Garbage collector methods

Hope you enjoyed reading this article. 



Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Garbage Collection - Automatic memory management

 Unknown     4:44 AM     .Net Architechture     6 comments   

While thinking of this question few things are coming in my mind ~ How .Net reclaims objects and memory used by an application ? So the answer is Garbage Collector

Memory management is the main part of CLR and Garbage Collector does the job for CLR. Garbage Collector attempts to reclaim garbage memory or memory occupied by objects those are no longer use by the application.

Advantages of Garbage Collector
  1. Allocates memory efficiently in Managed Heap
  2. Reclaims objects that are no longer be used by the application and keeps the memory available for other objects.
  3. You do not need to worry about memory. You just write your code GC will take care of the things.
  4.  Provides safe memory so that an object can not use content of another one.
 By default on 32 bit system each process can have 2 GB of virtual address space and on 64 bit system process can have 8 TB of address space( There is lot more concepts behind to that in case if you are interested then visit here. As .net application developer you deal with virtual address space only, never communicate with the physical memory. Virtual address space is divided into some fragments called blocks. So when application request to allocate memory GC look after these blocks and tries to find single block that is large enough to fulfill your need. It will be unsuccessful to allocate memory if virtual memory allocation manager doesn't find single block.Each proccess has its own managed heap.

When Garbage Collection Occurs ?

  1. When system has low physical memory
  2. When a process is initialized run time reserves a contiguous region of address space that initially has no storage allocated for it. This region is known as managed heap. The heap maintains a pointer - NextObjPtr. This pointer indicates where the next object is to be allocated within the heap. Initially, this pointer is set to the base address of the managed heap.
When ever you creates an object in the application, operator makes sure that managed heap have enough space to store this object in reserved address space region. If that object get fits in the managed heap then NextObjPTR increments itself to point to new location. If managed heap doesn't have enough space to store the object or object can not be fit it the reserved space region then garbage collection must be performed. The heap detects this by adding the size of the new object to NextObjPtr. If pointer is beyond the end of the region, then the heap is full and a collection must be performed.
         
So now you know how Garbage Collection performed in an application but this was the over view. Garbage collector maintains some generations to manage objects. So now the question comes into the mind :

How Garbage Collector reclaims memory ?

The Garbage Collector checks whether the object in heap is still in use or it's dead or not being used by the application. If it's not being used by the application then Garbage Collector claims that memory. So now the question comes in the mind How GC knows whether this object is in use or not ?

So each application has some set of application roots and these roots are maintained by CLR. These are kind of pointers those points to the storage location and those location refer objects. If those objects are null then GC reclaims that.

Application Roots: Global objects, static pointers and local object pointers that resides under thread stack are considered as application roots. From these roots GC identifies the dead objects.


Now we can see that Application roots are pointing to four objects : Object c, object D, Object F and Object H but Object C is pointing towards Object G as well. So these objects are still referring in the application but other objects are dead or not referring in the application. GC marked those objects as Garbage. So this was the first phase of GC known as Marking Phase.

Second stage is Relocation and Compaction : In this GC traverse linearly through the Heap, looking for memory blocks of Garbage objects and consider it as free memory. Now shifts all the non garbaged objects down in the heap and update the references to the objects using memcpy method. Lets look over the new graph after this phase -

                                 
GC only occurs when managed heap is full. So that's how GC algorithm works. Now GC also have Generation concepts to improve performance.

Generation 0: It's a youngest generation and contains all newly created objects.

Generation 1: Objects, who survives after next GC occurs, then they promote to Generation 1.

Generation 2: It's for long lived objects like objects those exists through out the application like static objects.
  
I will talk more about Generations in my Next article.

Hope you enjoyed this article.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

About The Author

Unknown
View my complete profile

Total Pageviews

Popular Posts

  • Predicate delegate in C#
    Hello Everyone, In the article we will talk about Predicate delegate. Predicate is also a delegate which encapsulate a method that takes...
  • Clr - Common Language Runtime
    .Net framework provides a run time environment - CLR. Common language runtime takes the IL code from the compiler( language specific) and p...
  • Auto logout chrome extension for Gmail
    Hello Friends, In the last article we learned to create a sample chrome extension. Here we are going to create auto logout Gmail script as...
  • Nagarro Placement Papers..
    Ques.1 :- Seat Reservation prog for the theatre. Write a function for seat allocation for the movie tickets. Total no of seats available are...
  • .Net Framework overview
    Hello friends : Here i am writing my first article on .Net framework anyways....So the question is What is .Net Framework ? The .Net fram...
  • What does it mean by disconnected data access architecture of ADO.Net?
    ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the databa...
  • C code to Check the string has valid identifier or not in.
    #include #include #include char keyword[][10]={"auto","break","case","char","const","...
  • Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ?
    Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate. In this article we will discuss w...
  • Delegates in C Sharp
    A Delegate is a type variable that holds the reference to a method. Delegates are similar to Pointer to functions in C and C++ When we...
  • Garbage Collection - Automatic memory management
    While thinking of this question few things are coming in my mind ~ How .Net reclaims objects and memory used by an application ? So the ans...

Blog Archive

  • ▼  2016 (4)
    • ▼  September (2)
      • ▼  Sep 03 (2)
        • Auto logout chrome extension for Gmail
        • Auto logout chrome extension for facebook
    • ►  August (1)
      • ►  Aug 28 (1)
    • ►  April (1)
      • ►  Apr 24 (1)
  • ►  2015 (12)
    • ►  September (10)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 27 (2)
      • ►  Sep 26 (3)
      • ►  Sep 20 (1)
      • ►  Sep 19 (1)
    • ►  August (1)
      • ►  Aug 16 (1)
    • ►  March (1)
      • ►  Mar 31 (1)
  • ►  2013 (10)
    • ►  June (1)
      • ►  Jun 16 (1)
    • ►  April (1)
      • ►  Apr 21 (1)
    • ►  February (8)
      • ►  Feb 18 (3)
      • ►  Feb 17 (2)
      • ►  Feb 16 (2)
      • ►  Feb 15 (1)
  • ►  2012 (1)
    • ►  May (1)
      • ►  May 27 (1)
  • ►  2010 (22)
    • ►  October (14)
      • ►  Oct 21 (1)
      • ►  Oct 06 (12)
      • ►  Oct 04 (1)
    • ►  April (2)
      • ►  Apr 22 (1)
      • ►  Apr 16 (1)
    • ►  March (1)
      • ►  Mar 30 (1)
    • ►  January (5)
      • ►  Jan 08 (3)
      • ►  Jan 01 (2)
  • ►  2009 (110)
    • ►  December (8)
      • ►  Dec 18 (2)
      • ►  Dec 05 (1)
      • ►  Dec 04 (5)
    • ►  November (1)
      • ►  Nov 27 (1)
    • ►  October (14)
      • ►  Oct 09 (4)
      • ►  Oct 07 (1)
      • ►  Oct 06 (3)
      • ►  Oct 05 (3)
      • ►  Oct 01 (3)
    • ►  September (17)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 25 (1)
      • ►  Sep 24 (1)
      • ►  Sep 17 (2)
      • ►  Sep 15 (3)
      • ►  Sep 11 (2)
      • ►  Sep 09 (3)
      • ►  Sep 08 (2)
    • ►  August (31)
      • ►  Aug 31 (1)
      • ►  Aug 27 (3)
      • ►  Aug 26 (1)
      • ►  Aug 25 (2)
      • ►  Aug 24 (1)
      • ►  Aug 22 (2)
      • ►  Aug 21 (3)
      • ►  Aug 20 (2)
      • ►  Aug 19 (3)
      • ►  Aug 18 (1)
      • ►  Aug 16 (1)
      • ►  Aug 12 (2)
      • ►  Aug 11 (1)
      • ►  Aug 10 (3)
      • ►  Aug 07 (4)
      • ►  Aug 06 (1)
    • ►  July (24)
      • ►  Jul 25 (4)
      • ►  Jul 24 (20)
    • ►  April (15)
      • ►  Apr 10 (3)
      • ►  Apr 07 (9)
      • ►  Apr 06 (3)

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments
copyright @ TechGiant 2015. Powered by Blogger.

Disclaimer

This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Followers

Copyright © A Developer Journey who codes for fun | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com