Boxing and unboxing in c# with simple example

What is boxing and UnBoxing ?

The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

int Val = 1;
  Object Obj = Val; 

int Val = 1;
  Object Obj = Val; //Boxing
  int i = (int)Obj; //Unboxing

What is the difference between ref & out parameters?

An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.

What is the difference between Array and Arraylist?

In an array, we can have items of the same type only. The size of the array is fixed. An arraylist is similar to an array but it doesn’t have a fixed size.

What is the difference between an EXE and a DLL?

Dll is an In-Process Component whereas EXE is an OUt-Process Component.Exe is for single use whereas you can use Dll for multiple use.
Exe can be started as standalone where dll cannot be.

Types of comments in C#?

* Single line comments:
// for single line comments

* Multiple line comments:
/* for multi line comments */

* XML tags comments:
/// XML tags displayed in a code comment

What is serialization?

When we want to transport an object through network then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should inherit ISerialize Interface.
De-serialization is the reverse process of creating an object from a stream of bytes.

How does object pooling and connection pooling differ?

In Object pooling, you can control the number of connections. In connection pooling, you can control the maximum number reached. When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread. In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy.

What is Anonymous Method ?

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are basically methods without a name, just the body.
it is also called inline method

delegate void NumberChanger(int n);
namespace DelegateAppl
class TestDelegate
static int num = 10;
public static void AddNum(int p)
num += p;
Console.WriteLine("Named Method: {0}", num);

public static void MultNum(int q)
num *= q;
Console.WriteLine("Named Method: {0}", num);
public static int getNum()
return num;
static void Main(string[] args)
NumberChanger nc = delegate(int x)
Console.WriteLine("Anonymous Method: {0}", x);
nc =  new NumberChanger(AddNum);
nc =  new NumberChanger(MultNum);

Anonymous Method: 10
Named Method: 15
Named Method: 30

Read More

Exception handling in C Sharp

Exception handling in C Sharp

Exception handling the C Sharp language exception handling features provide a way to deal with any unexpected or exceptional situation that arise while a program is running is exception handling uses that try catch and finally keyword to attempt action that may not succeeded to handle failure and the cleanup resource afterwards.

Exception handling in C Sharp  

Exception can be generated by the Common Language Runtime (CLR) by third party library or by the application code using the throw keyword.

In I have an exception class this is base class in system namespace exception class handle the all kind of exception during application execution.

Properties of Exception class

Data: Get a collection of key value pairs that provide additional user defined information about the exception.
HelpLink: Gets or sifts a link to help file associated with this exception.
HResult: Gets or sets HResult,a coded numeric value that is assigned to a specific exception. 
InnerException: Gets the exception instance that caused the current exception.
Message: Gets a message that describe current exception. 
Source: Gets or sets the name of application or the object that causes the error.
StackTrace: Getting representation of the immediate frame on the call stack.
TargetSite: Gets the method that through the current exception.

How to use Exception in programming

1.Try Block
2.Catch Block
3.Finally Block
4.Throw Keyword

Try Block:

   //statement that can cause Exception

Catch Block:

catch(Exception Ex)
   //statement to handle the exception

Finally Block:

  //Statement to clean Up

Throw Keyword:

catch(Exception Ex)

Some Important points about Exception Handling

1.Exception are types that all directly or indirectly derived from System.Exception class.
2.Exception object contains detailed information about the error, such as the state of the call stack and a text description of the error.
3.A try block is used to throw multiple exception that can handle by using multiple catch blocks.
4.More specialized catch block should come before a generalized one otherwise a catch block will never be executed.
5.Exception can be generated by a program by using the throw keyword.
6. If no exception handling mechanism is used, the program stops executing with an error message.
7.By providing a catch block without a brackets or arguments, we can catch all exception occurred inside a try block.

A simple program of Exception Handling

using System.Linq;
using System.Text;
using System.Threading.Tasks;

    class Program
        static void Main(string[] args)
            int num1 = 100;
            int num2 = 0;
                Console.WriteLine("Division of {0} by {1} is : {2}", num1, num2, num1/num2);
            catch (Exception ex)

Attempted to divide by zero.   
Press any key to continue . . .

In this program occurs an exception (DivideByZeroException) in  Try Block and Catch Block handle the exception. And display the message of the Exception.

Also Read:

Read More

Collection in c# | Type of collection

Collection in c# 

type of collection in c#

Collection provide a more flexible way to work with group of objects unlike array, the group of object you work can grow and shrink directly as the need of application change. 

For some collections, you can assign it to an object that you put into the collection so that you can quickly retrive the object by using the key.

Acollection is a class,you must declare a new collection before you can add element to that collection.

If your Collection contain elements of only on data type,you can use one of the classes in the System.Collection.Generics namespace.

A collection enforces type safety so that no other data type can be added to it. When you retrive an element from a generics collection collection,you do not have determine if data type for convert it.

Type of collection

Many common collection are provided by the .NET Fremework. Each type of collection is designed for a specific purpose. The following groups of collection classes are described in this section.

  • System.Collection.Generics
  • System.Collection

System.Collection class:

The classes in the System.Collection namespace do not store elements as specially typed objects,but as objects of type Object.

Whenever possible,you should use the generics collection in the System.Collection.Generics namespace or the System.Collection.Concurrent namespace instead of the legacy types in the System.Collection namespace.

Their are some frequently used classes in the System.Collection namespace.

#Queue:  Represents a first in, first out (FIFO) collection of object.
#Stack:    Represents a list in,first out (LIFO)  collection of object.
#ArrayList: Represents an array of objects whose size is dynamically increased as required.
#HasTable:  Represents a collection of key/value pairs the are organised based on the hash code of   the key.

System.Collection.Generic class:

You can create a generics collection by using on of the classes in the System.Collecion.Generic namespace. A generics collection is useful when every item in the collection had the same data type.
A generic collection enforces strong typing by allowing only the desired data type to be added.

Their are some frequently used classes in the System.Collection.Generic namespace.

#Dictionary<T Key, T Values>: Represents a collection of key/value pairs that are organized based on the key.
#List<T>: Represent a collection of object that can be accessed by index. Provides method  to search ,short and modify lists.
#Queue<T>: Represents a first in,first out (FIFO) collection of objects.
#Stack<T>: Represents a last in. first out (LIFO) collection of objects.


Generic allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in our program. In other word, generic allow you to write a class or method that can work with any data type.

You write the specification for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type. 

Features of Generic

Generic is a technique that enriches your program in the following ways:

1. It helps you to maximize code reuse,type safety and performance.
2. You can create your own generic interfaces,classes,methods,events and delegate.
3. You may create generic classes constrained to enable access to method on particular data types.
4. You may get information on the types used in a generic data type at run-time by means of reflection.

Read More:

Read More

What is MVC - A small tutorial

What is MVC 

What is MVC the model view controller it is better to separate an application into three main components.

The model
The view
The controller 

What is MVC

The MVC Framework provide an alternative to the webform pattern for creating web application the MVC framework is a lightweight, highly testable presentation framework that is integrated with existing features, such as master page and membership based authentication. The MVC Framework is defined in the System.web.mvc assembly . Full control over HTML JavaScript and css it is better as well as recommended approach for large scale application where different teams are working together.

Asp.Net Mvc reference namespace

System.Web.Mvc: Contains class and interfaces that support the MVC pattern for web application. This namespace includes classes that represent controllers, controller factories, action results,views, partial views and model model binders

System.Web.Mvc.Ajax: Contains classes that support ajax script in an MVC application. That namespace includes support for ajax script and ajax option settings

System.Web.Mvc.Async: Contains classes and interfaces that support asynchronous action in an MVC application.

System.Web.Mvc.Html: Contents classes that helper render HTML control in an MVC application. The namespace includes classes that support forms, input control, links, partial view and validation.

MVC Architechture

An MVC application have three main folders which is model,view and Controller and also be have more folder to place script file and App_Start and much more so let's talk about these folders.


Model is used to store Data classes which is created by SQL or entity framework or may be reference of service from WCF or many more at last we just use model to represent the data schema for a view or partial view.


View folder is used to store the view page or partial view page for a particular Action is declared into controller class, Basically view folder maybe contains a shared Folder also in which we can store to common pages or user control that can be used into any controller every request for a view or partial view page from an Action method is also check the page extension into shared folder also.


Controller is just used to store some business logic class controller is a collection of only classes and every class is a child class of System.Web.Mvc.Controller class, a controller class is only contain some method known as Action method which is responsible to return a View, Partial view, Content JSON Data and much more.

Action method in MVC

Action method are the only a special type of method which is used write the code for a particular task and after that is also responsible to returns something to the user and that can be a page or partial page any action handle the two type of http request.

1.Http Get 
2.Http Post 

Http Get: Http Get action is only used to handle this request are come directly from user and also we can say those request come at first time for an Action method.

Http Post: Http Post action is only call call at that time when any already you exist on client side and user will submit an HTML form by Anthony submit type button so at the time that type of action will call and that can also written the all control value in Form Collection type object from HTML form 

An action method may use type of return type to return different-different type of info or value to the user we have some many type of returned from an action to user but maximum time we will use Action Result because it's a parent type any other type which can be used in an action method as a return type 

Action Result is an abstract class that can have serval subtype

Action Result SubTypes:

ViewResult: Renders a specified for the user.
EmptyResult: An empty response returned.

PartialViewResult: Renders a specified partial view to the response stream. 
RedirectToRouteResult: Perform Http redirection to URL that is determined by the routing engine based on given route data.

Jason result: serial as a given view data object to JSON format.
JavaScriptResult : Return a piece of JavaScript code that can be executed on the client side.

ContentResult: Write content to the response stream without requiring and view.
FileContentResult: Returns a file to the client.
FileStreamResult: Written a file to the client which is provided by a string. 

Advantage of MVC framework

1. It makes very easy to manage complexity by dividing an application into the model ,view and the       controller.
2. It does not use Viewstate or server side forms.
3. Full control over HTML JavaScript and css.
4. It provides better support for test driven development(TDD).
5. It works well for web application that are supported by large team of developer and for web designer who need a high degree of control over the application behaviour.
6. By default support of Facebook and Google authentication.
7. It easy to manage ilaj application to dividing in multiple areas.

Read More:

Read More

How do you retrieve two tables of data at the same time by using data reader

Retrieve two tables of data at the same time by using data reader

Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.

The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table. The following code shows you how do it.

//Create the SQL Query with 2 Select statements
string SQLQuery = "Select * from Customers;Select * from Employees;";
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand(SQLQuery, ConnectionObject);
//Open the connection
//Execute the command. Now reader object will have 2 tables of data.
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
//Loop thru the tables in the DataReader object
while (ReaderObject.NextResult())
while (ReaderObject.Read())
//Do Something
//Close the Reader
//Close the Connection

See More:

Read More

Cookies in - All about HttpCookies

Cookies in cookies is a small piece of information stored on the client machine.The HttpCookie class is under System.Web namespace. It contains properties and methods necessary to work with individual cookies.Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. Length of the text stored in cookies is 4096(4kb) in general but could vary from browser to browser.

Cookies are small text files that a is transferred by the site you visit or internet service provider and saved to your computer's hard drive with the help of web browser. You need to allow your site to save the file to your system. The site/ service provider recognizes your web browser and capture, remembers and stores specific information.

With the help of cookies, only the website can remember your Wishlist items, products stored in your shopping cart, your recent activity list and preferences that ultimately help us improve our service and your browsing experience. With the help of cookies, we compile site traffic and site visitors’ interaction data.

Remember, third party sites are not provided your personal information stored with us, but we may use the information and contact external websites to improve the services we offer and assist you better.

Cookies can be enabled or disabled through your browser settings. In case you face any issues look for browser help menu and search how to modify cookies settings. Turning off cookies will refrain you from features that help improve site experience and services provided to you. You can still place orders over the telephone by contacting customer service.

Cookies in

Persistent and Non-persistent cookies in ASP.NET

There two type of cookies in ASP.NET

Persistent cookies: cookies are stored on your computer hard disk.They stay on your hard disk and can be accessed by web servers until they are deleted or have expired.

public void PersistentCookies(string name, string value)
 HttpCookie cookie = new HttpCookie(name);
 cookie.Value = value;
 cookie.Expires = Convert.ToDateTime("12/12/2008");

Non-persistent cookies: cookies are saved only while your web browser is running.  They can be used by a web server only until you close your browser.They are not saved on your disk.

public void NonPersistentCookies(string name, string value)

    HttpCookie cookie = new HttpCookie(name);
    cookie.Value = value;

Read More

How to call javascript function in anchor tag href

Call javascript function in anchor tag href

<title>Call javascript function in anchor tag  href:Examples</title>
<p><a href="javascript:void(''))">
Open a new window.</a></p>


Read More

Call javascript function in body onload event : body onload javascript

Call javascript function in body onload event 

<title> body onload javascript</title>
<script type="text/javascript">

    function demo() {


<body onload="demo();">
Read More

Difference between Const and ReadOnly in c#

Difference between Const and ReadOnly

Const in c#
  • You have to initialize const variables while declaration.
  • You cannot reassign a const variable.
  • Compiler evaluates the const variables.
  • The static modifier is not allowed in a constant declaration.
  • A const field of a reference type other than string can only be initialized with null.

Example for const in

using System;
using System.Text;

namespace ProgramCAll

    class ProgramCall
        /*A const field of a reference type other than string
        can only be initialized with null*/
        private const StringBuilder myName = null;

        public static void Main()
            //You have to initilize Const varabiles while declartion
            const int myEmpId = 173524;

            //Valid scenario
            const int myNumber = 10 + 16;

            const string myName = "John";

            // Reassigning a const variable is not allowed.
            //Comment out below code to run the program
            myEmpId = 23456;



Readonly in c#
  • readonly fields can be initialized only while declaration or in the constructor.
  • Once  you initialize a readonly field, you cannot reassign it.
  • You can use static modifier for readonly fields
  • readonly modifier can be used with reference types
  • readonly modifier can be used only for instance or static fields, you cannot use readonly keyword for variables in the methods.

Example for readonly modifier in

using System;
using System.Text;

namespace ProgramCall
    class MyClass
        //readonly can only be used with instance or static variables
        public readonly int mynumber = 10;
        public readonly int addnumber = 10 + 15;

        //readonly modifier can be used with static varaibles       
        public static string myEmployer = "ProgramCall.Com";

        //readonly can be used with reference types
        public readonly StringBuilder name = new StringBuilder("John");

        /*  readonly varaible can be intilized in constructor but
             cannot be declared in constructor    */
        public readonly string myName;

        //readonly fields can be initlized in constructor
        public MyClass(string name)
            myName = name;


        private void myMethod()
            /* readonly modifier cannot be used in method level variables
           the below line throws a error. */
            //  readonly int num = 5;


    //main class
    class ProgramCall

        public static void Main()
            MyClass obj = new MyClass("Bill");


Difference between const and readonly
  • const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
  • const variables can declared in methods ,while readonly fields cannot be declared in methods.
  • const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
  • A const field is a compile-time constant, the readonly field can be used for run time constants.
Read More