Private constructor in c#


Private constructor in c# is a special type of function which name same as the class name. If any class having private constructor it means that we can't create the object of that class. Over you if you want to create the object of class which have private constructor then you have to take a default constructor in your class.

Private constructor in c# is a special type of function which name same as the class name. If any class having private constructor it means that we can't create the object of that class. Over you if you want to create the object of class which have private constructor then you have to take a default constructor in your class

(see the real time example of private constructor).

  public class Program
    {
        private Program(int a, int b)
        {
            a = 10;
            b = 11;
        }
        public Program()
        {
       
        }
    }
    class testing
    {
        static void Main(string[] args)
        {
            Program p = new Program();

        }

    }



Classes Which Loads Only one Time In memory. In Singleton Class Constructor Is Always Private and Object Is Always Static.

Imp. Point:

1.In Singleton Class We Have Only One Object Of A Class.
2.Singleton Class Uses Static so it’s Behavior Is Static.

namespace WindowsFormsApplication3
{

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 ob = Class1.Create();
            Class1 ob1=Class1.Create();
            Class1 ob2=Class1.Create();
        }
    }

    public class Class1
    {
        Class1()
        {
        }
        static Class1 ob;

        public static Class1 Create()
        {
            if (ob == null)
            {
                ob = new Class1();
                return ob;
            }
            else
           {
            return ob;
            }
        }
    }
}

Can constructor be private
                                         -Yes

Can a Private Constructor have Parameters ?   
                                                                      -Yes.



Must Read :





Read More

Website is in Under Construction Page HTML


Website is in Under Construction Page HTML


Website is in Under Construction Page






<html>
<head>
     <title>
     Website is in Under Construction
     </title>
</head>
<body style="background-color:#f0ecf5s;">

<br/>
<br/>
<br/>
<br/>
<br/>

<h1 style="Color:red; font-weight:bold; width=100%;">

<marquee style="width=100%;" scrollamount="1" direction="up" behavior="alternate" scrolldelay="1">
<marquee style="width=100%;" scrollamount="1" direction="right" behavior="alternate"  scrolldelay="1">

" Website is in Under Construction"
<br/>
<br/>
<br/>

Contact No:12212....

</marquee></marquee>
</h1>
<br/><br/><br/><br/>
</body>

 </html>

Copy and paste it in notepad and save it with .html extension. This is very simple under construction page.

Read More

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.

Boxing:
int Val = 1;
  Object Obj = Val; 

UnBoxing:
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
example:

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(10);
nc =  new NumberChanger(AddNum);
nc(5);
nc =  new NumberChanger(MultNum);
nc(2);
Console.ReadKey();
}
}
}

output:
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 C#.net 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:

try
{
   //statement that can cause Exception
}

Catch Block:


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


Finally Block:


finally
{
  //Statement to clean Up
}

Throw Keyword:


catch(Exception Ex)
{
   throw(e)
}


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;
            try
            {
                Console.WriteLine("Division of {0} by {1} is : {2}", num1, num2, num1/num2);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }


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:

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 asp.net MVC - A small tutorial

What is asp.net MVC 

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

The model
The view
The controller 


What is asp.net MVC



The ASP.net MVC Framework provide an alternative to the asp.net webform pattern for creating web application the ASP.net MVC framework is a lightweight, highly testable presentation framework that is integrated with existing asp.net 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 ASP.net 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 ASP.net 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 ASP.net 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 ASP.net 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:

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:

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:

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