Implement your own Generic list in C#

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)
            list[count - 1] = item;
        public void RemoveAt(int index)
            if (index > Count || index < 0)
                throw new IndexOutOfRangeException("Index is out of range.");
            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 > Count || index < 0)
                throw new IndexOutOfRangeException("Index is out of range.");
            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 > this.Capacity)
                this.Capacity = this.Capacity * 2;
                Array.Resize(ref this.list, this.Capacity);

Pass Value type parameters by value and by reference

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.

How does GC handles Circular References ?

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.

Strong Vs Weak References

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 :)

What is Common Type System ?

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.

What is Common Language Specification ?

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.

Garbage Collection - Automatic Memory Management Part II

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. 

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

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 provide to code to run time compiler called JIT. So lot of confusion you must be thinking about IL code & Jit ?

IL code is half compile or partially compile code. IL code will be same for all .Net framework languages whether application is developed using C#, VB or any other .Net framework language. .Net provides you this managed environment to write your code and get benefit from this.

In short CLR comes into the picture after .Net compiles the code and convert it into IL code and then CLR takes the responsibility does the operation and provide the code to JIT. JIT are the run time compilers that converts code to machine language.

Benefits of CLR -

1. Garbage Collection - Automatic memory management
2. Thread management
3. Common type system
4. CLS - provides ability to use components developed in different languages
5. Code Access Security (CAS)
5. Exception handling
6. It converts MSIL code to Native code and provides it to Just in time compiler

So now question arises how runtime knows about the code you write in a file and provides you these benefits so here the magic comes of Metadata.

When you write your code in .net environment and compile the code. .Net creates an assembly and assembly contains metadata. Metadata resides with the code and every loadable PE(executable) contains this metadata.Metadata contains binary information of the code. Every member defined in an assembly/ module metadata contains all this info. When code is executed, Run time loads this metadata into memory and get the reference about the code to do the above mentioned operations.

code that  managed in this way called managed code. In simple way if i say the code is taken care by CLR is managed code.

Hope you enjoyed reading this article. Please provide me your feedback if you find it interesting.

.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 framework is a software framework / technology that supports multiple languages and designed to develop window, web & mobile apps in short next generation applications.

Points to remember:

1. It provides consistent environment to write applications in multiple languages.
2. It provides consistent OOPS environment
3. It provides an environment to reduce development effort, eliminates performance problems, provides you automatic memory management.
4. .Net ensures all communication as per industry standards so that apps can easily communicate with other frameworks/ technologies.

.Net framework consists of two important concepts : CLR and framework class libraries.

1. CLR : is the heart of .Net that takes care of code execution & services like - memory management, thread management, code access security(CAS model) & Type safety.
2. Framework Library : classes, interfaces, base data type, exceptions, perform I/O, rich gui, mostly .Net framework library is CLS compliance and can directly/indirectly interacts from any other programming languages.

I will discuss more about CLR and framework libraries in later of my articles. Hope you enjoy reading this article.

Happy Coding
Image reference from - here

What is Var keyword in C#

Var is an implicit data type. It means var can represent any data type that can represent at compile time. So it means var does compile time type casting.

Lets look on some code :

So now we can easily see that from the above code we can not implicitly convert string to int. If we check this with ILDASM tool then we will not see any var keyword in IL code. .Net will treat this as Int variable.
Some more point to notice about var :

1. We can not assign null to var keyword.
2. We can not pass var as a parameter of the method.
3. We can not define return type as var in our method.
4. There is no performance issue with var as .Net execution engine doesn't bother about Var. It will treat it as int or the type we defined at compile time.
 Var mystring = "mystring"; will define mystring as string variable.

Happy Coding Hours

C# IQ - What do you mean by Null-Coalescing operator ?

How we represent Null-Coalescing operator : ??

This is a replacement for ternary operator. If we want to check null value using ternary then we do :

string myString = null;

string value = myString == null ? "My string is null" : myString ;

Using Null-Coalescing :

string value = myString ?? "My string is null";

Saurabh Singh

Tech-Giant(Jargons.. for .Net Professionals): How do I define a data adapter?

How do I define a data adapter?

The data adapter stores your command (query) and connection and using these connect to the database when asked, fetch the result of query and store it in the local dataset.
The DataAdapter class (SqlDataAdapter, OracleDataAdapter, OleDbDataAdapter, OdbcDataAdapter) may be instantiated in three ways:
1. by supplying the command string (SQL Select command) and connection string
2. by supplying the command string (SQL Select command) and a connection object
3. by supplying the command object (SqlCommand, OracleCommand, OleDbCommand, OdbcCommand)
For example, with SQL Server, the data adapter is created as
C# Version
// for Sql Server
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, conn);

What is a data reader?

The data reader is a component that reads the data from the database management system and provides it to the application. The data reader works in the connected manner; it reads a record from the DB, pass it to the application, then reads another and so on.

What is a database command?

A database command specifies which particular action you want to perform to the database. The commands are in the form of SQL (Structured Query Language). There are four basic SQL statements that can be passed to the database.

What is a database connection?

A database connection represents a communication channel between you application and database management system (DBMS). The application uses this connection to pass the commands and queries to the database and obtain the results of the operations from the database.

What is a data adapter?

A data adapter is the component that exists between the local repository (dataset) and the physical database. It contains the four different commands (SELECT, INSERT, UPDATE and DELETE). It uses these commands to fetch the data from the DB and fill into the dataset and to perform updates done in the dataset to the physical database. It is the data adapter that is responsible for opening and closing the database connection and communicates with the dataset.

What is a dataset?

A dataset is the local repository of the data used to store the tables and disconnected record set. When using disconnected architecture, all the updates are made locally to dataset and then the updates are performed to the database as a batch.

DataSet or DataReader ?

The data reader is more useful when you need to work with large number of tables, database in non-uniform pattern and you need not execute the large no. of queries on few particular table.
When you need to work on fewer no. of tables and most of the time you need to execute queries on these fewer tables, you should go for the dataset.
It also depends on the nature of application. If multiple users are using the database and the database needs to be updated every time, you must not use the dataset. For this, .Net provides the connection oriented architecture. But in the scenarios where instant update of database is not required, dataset provides optimal performance by making the changes locally and connecting to database later to update a whole batch of data. This also reduces the network bandwidth if the database is accessed through network.
Disconnected data access is suited most to read only services. On the down side, disconnected data access architecture is not designed to be used in the networked environment where multiple users are updating data simultaneously and each of them needs to be aware of current state of database at any time (e.g., Airline Reservation System).

What's the difference between accessing data with dataset or data reader?

The dataset is generally used when you like to employ the disconnected architecture of the ADO.Net. It reads the data into the local memory buffer and perform the data operations (update, insert, delete) locally to this buffer.
The data reader, on the other hand, is directly connected to the database management system. It passes all the queries to the database management system, which executes them and returns the result back to the application.
Since no memory buffer is maintained by the data reader, it takes up fewer resources and performs more efficiently with small number of data operations. The dataset, on the other hand is more efficient when large number of updates are to be made to the database. All the updates are done in the local memory and are updated to the database in a batch. Since database connection remains open for the short time, the database management system does not get flooded with the incoming requests.

What does it mean by connected data access architecture of ADO.Net?

In the connected environment, it is your responsibility to open and close the database connection. You first establish the database connection, perform the interested operations to the database and when you are done, close the database connection. All the changes are done directly to the database and no local (memory) buffer is maintained.

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 database system and then interact with it through SQL queries using the connection. The application stays connected to the DB system even when it is not using DB services. This commonly wastes the valuable and expensive database resource as most of the time applications only query and view the persistent data. ADO.Net solves this problem by managing a local buffer of persistent data called data set. Your application automatically connects to the database server when it needs to pass some query and then disconnects immediately after getting the result back and storing it in dataset. This design of ADO.Net is called disconnected data architecture and is very much similar to the connection less services of http over the internet. It should be noted that ADO.Net also provides the connection oriented traditional data access services.
Traditional Data Access Architecture

ADO.Net Disconnected Data Access Architecture

Another important aspect of the disconnected architecture is that it maintains the local repository of data in the dataset object. The dataset object stores the tables, their relationship and different constraints. The user performs operations like update, insert, delete to this dataset locally and finally the changed dataset is stored in actual database as a batch when needed. This greatly reduces the network traffic and results in the better performance.

Difference between value type and reference type ?

Many programming languages provide built-in data types such as integers and floating-point numbers. These are copied when they are passed in to arguments i.e. they are passed "By Value". In .NET terms, these are called Value Types".
The RunTime supports two kinds of Value Types:
1 Built-in value types
The .NET Framework defines built-in value types such as System.Int32 and System.Boolean which correspond and are identical to primitive data types used in programming languages.
2 User-defined value types
The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.
The following are the Reference Types:
• class
• interface
• delegate
This following are the "built-in" Reference Types:
• object
• string

What is serialization in .NET and what are the ways to control serialization?

Serialization is the process of converting an object into a stream of bytes. On the other hand Deserialization is the process of creating an object from a stream of bytes. Serialization/Deserialization is used to transport or to persist objects. Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly are converted to a stream of bytes. Which is then written to a data stream. Upon the object's subsequent deserialized, an exact clone of the original object is created.
Binary serialization preserves Type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example: An object can be shared between different applications by serializing it to the clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so forth. Remoting uses serialization to pass objects "By Value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve Type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.
As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.