Saturday, 24 September 2011

Its all about Lists

You have questions about the List collection in the .NET Framework, which is located in the System.Collections.Generic namespace. You want to see examples of using List and also explore some of the many useful methods it provides, making it an ideal type for dynamically adding data. This document has lots of tips and resources on the List constructed type, with examples using the C# programming language.
Key points: Lists are dynamic arrays in the C# language. They can grow as needed when you add elements. They are considered generics and constructed types. You need to use < and > in the List declaration.

Add values

To start, we see how to declare a new List of int values and add integers to it. This example shows how you can create a new List of unspecified size, and add four prime numbers to it. Importantly, the angle brackets are part of the declaration type, not conditional operators that mean less or more than. They are treated differently in the language.
Program that adds elements to List [C#]

using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<int> list = new List<int>();
 list.Add(2);
 list.Add(3);
 list.Add(5);
 list.Add(7);
    }
}
Adding objects. The above example shows how you can add a primitive type such as integer to a List collection, but the List collection can receive reference types and object instances. There is more information on adding objects with the Add method on this site.
List Add MethodFor loop.

Loops

Here we see how you can loop through your List with for and foreach loops. This is a very common operation when using List. The syntax is the same as that for an array, except your use Count, not Length for the upper bound. You can also loop backwards through your List by reversing the for loop iteration variables. Start with list.Count - 1, and proceed decrementing to >= 0.
Program that loops through List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<int> list = new List<int>();
 list.Add(2);
 list.Add(3);
 list.Add(7);

 foreach (int prime in list) // Loop through List with foreach
 {
     Console.WriteLine(prime);
 }

 for (int i = 0; i < list.Count; i++) // Loop through List with for
 {
     Console.WriteLine(list[i]);
 }
    }
}

Output
    (Repeated twice)
2
3
7

Count elements

To get the number of elements in your List, access the Count property. This is fast to access, if you avoid the Count() extension method. Count is equal to Length on arrays. See the section "Clearing List" for an example on using the Count property.

Clear List

Here we see how to use the Clear method, along with the Count property, to erase all the elements in your List. Before Clear is called, this List has 3 elements; after Clear is called, it has 0 elements. Alternatively, you can assign the List to null instead of calling Clear, with similar performance. However, after assigning to null, you must call the constructor again.
Program that counts List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<bool> list = new List<bool>();
 list.Add(true);
 list.Add(false);
 list.Add(true);
 Console.WriteLine(list.Count); // 3

 list.Clear();
 Console.WriteLine(list.Count); // 0
    }
}

Output

3
0

Copy array to List

Here we see an easy way to create a new List with the elements in an array that already exists. You can use the List constructor and pass it the array as the parameter. List receives this parameter, and fills its values from it.
Program that copies array to List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 int[] arr = new int[3]; // New array with 3 elements
 arr[0] = 2;
 arr[1] = 3;
 arr[2] = 5;
 List<int> list = new List<int>(arr); // Copy to List
 Console.WriteLine(list.Count);       // 3 elements in List
    }
}

Output
    (Indicates number of elements.)

3
Notes. It is useful to use the List constructor code here to create a new List from Dictionary keys. This will give you a List of the Dictionary keys. The array element type must match the type of the List elements, or the compiler will refuse to compile your code.

Find elements

Here we an example of how you can test each element in your List for a certain value. This shows the foreach loop, which tests to see if 3 is in the List of prime numbers. Note that more advanced List methods are available to find matches in the List, but they often aren't any better than this loop. They can sometimes result in shorter code.
List Find Method
Program that uses foreach on List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // New list for example
 List<int> primes = new List<int>(new int[] { 2, 3, 5 });

 // See if List contains 3
 foreach (int number in primes)
 {
     if (number == 3) // Will match once
     {
  Console.WriteLine("Contains 3");
     }
 }
    }
}

Output

Contains 3

Capacity

You can use the Capacity property on List, or pass an integer into the constructor, to improve allocation performance when using List. My research shows that capacity can improve performance by nearly two times for adding elements. Note however that this is not usually a performance bottleneck in programs that access data.
Capacity Property
TrimExcess method. There is the TrimExcess method on List as well, but its usage is very limited and I have never needed to use it. It reduces the memory used. Note: "The TrimExcess method does nothing if the list is at more than 90 percent of capacity".
msdn.microsoft.com

BinarySearch

You can use the binary search algorithm on List with the instance BinarySearch method. Binary search uses guesses to find the correct element much faster than linear searching. It is often much slower than Dictionary.
BinarySearch List

AddRange and InsertRange

You can use AddRange and InsertRange to add or insert collections of elements into your existing List. This can make your code simpler. See an example of these methods on this site.
List AddRange Use

ForEach method

Foreach loop construct.
Sometimes you may not want to write a regular foreach loop, which makes ForEach useful. This accepts an Action, which is a void delegate method. Be very cautious when you use Predicates and Actions, because they can decrease the readability of your code.
Another useful method. There is a TrueForAll method that accepts a Predicate. If the Predicate returns true for each element in your List, the TrueForAll method will return true also. Else, it will return false.

Join string List example

Here we see how you can use string.Join on a List of strings. This is useful when you need to turn several strings into one comma-delimited string. It requires the ToArray instance method on List. The biggest advantage of Join here is that no trailing comma is present on the resulting string, which would be present in a loop where each string is appended.
Program that joins List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // List of cities we need to join
 List<string> cities = new List<string>();
 cities.Add("New York");
 cities.Add("Mumbai");
 cities.Add("Berlin");
 cities.Add("Istanbul");

 // Join strings into one CSV line
 string line = string.Join(",", cities.ToArray());
 Console.WriteLine(line);
    }
}

Output

New York,Mumbai,Berlin,Istanbul

Get List from Keys in Dictionary

Here we see how you can use the List constructor to get a List of keys in your Dictionary collection. This gives you a simple way to iterate over Dictionary keys, or store them elsewhere. The Keys instance property accessor on Dictionary returns an enumerable collection of keys, which can be passed to the List constructor as a parameter.
Program that converts Keys [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // Populate example Dictionary
 var dict = new Dictionary<int, bool>();
 dict.Add(3, true);
 dict.Add(5, false);

 // Get a List of all the Keys
 List<int> keys = new List<int>(dict.Keys);
 foreach (int key in keys)
 {
     Console.WriteLine(key);
 }
    }
}

Output

3, 5

Insert elements

Here we see how you can insert an element into your List at any position. The string "dalmation" is inserted into index 1, which makes it become the second element in the List. Note that if you have to Insert elements extensively, you should consider the Queue and LinkedList collections for better performance. Additionally, a Queue may provide clearer usage of the collection in your code.
Program that inserts into List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<string> dogs = new List<string>(); // Example List

 dogs.Add("spaniel");         // Contains: spaniel
 dogs.Add("beagle");          // Contains: spaniel, beagle
 dogs.Insert(1, "dalmation"); // Contains: spaniel, dalmation, beagle

 foreach (string dog in dogs) // Display for verification
 {
     Console.WriteLine(dog);
 }
    }
}

Output

spaniel
dalmation
beagle

Remove elements

The removal methods on List are covered in depth in another article on this site. It contains examples for Remove, RemoveAt, RemoveAll, and RemoveRange, along with my notes.
List Remove Methods

Sort and reverse

Sorted letters: A through Z.
You can use the powerful Sort and Reverse methods in your List collection. These allow you to order your List in ascending or descending order. Additionally, you can use Reverse even when your List is not presorted. There is more information on these topics, as well as sorting your List with LINQ on a property on this site.
Sort List Method

Convert List to array

Array type.
You can convert your List to an array of the same type using the instance method ToArray. There are examples of this conversion, and the opposite, on this site.
Convert List to Array List CopyTo Method

Get range of elements

Here we see how you can get a range of elements in your List collection using the GetRange instance method. This is similar to the Take and Skip methods from LINQ, but has different syntax.
Program that gets ranges from List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<string> rivers = new List<string>(new string[]
 {
     "nile",
     "amazon",     // River 2
     "yangtze",    // River 3
     "mississippi",
     "yellow"
 });

 // Get rivers 2 through 3
 List<string> range = rivers.GetRange(1, 2);
 foreach (string river in range)
 {
     Console.WriteLine(river);
 }
    }
}

Output

amazon
yangtze

List with DataGridView

You can use the List type with a DataGridView collection in Windows Forms. Sometimes, though, it is better to convert your List to a DataTable. For a List of string arrays, this will make the DataGridView display the elements correctly.
Convert List to DataTable, Use DataGridView

Test Lists for equality

Sometimes you may need to test two Lists for equality, even when their elements are unordered. You can do this by sorting both of them and then comparing, or by using a custom List equality method. This site contains an example of a method that tests lists for equality in an unordered way.
List Element Equality

List with structs

When using List, you can improve performance and reduce memory usage with structs instead of classes. A List of structs is allocated in contiguous memory, unlike a List of classes. This is an advanced optimization. Note that in many cases using structs will actually decrease the performance when they are used as parameters in methods such as those on the List type.
Var keyword.

Var

Here we see how you can use List collections with the var keyword. This can greatly shorten your lines of code, which sometimes improves readability. The var keyword has no effect on performance, only readability for programmers.
Program that uses var with List [C#]

using System.Collections.Generic;

class Program
{
    static void Main()
    {
 var list1 = new List<int>();       // <- var keyword used
 List<int> list2 = new List<int>(); // <- Is equivalent to
    }
}

Summary

In this tutorial, we saw lots of examples with the List constructed type. You will find that List is powerful and performs well. It provides flexible allocation and growth, making it much easier to use than arrays. In most programs that do not have memory or performance constraints and must add elements dynamically, the List constructed type in the C# programming language is ideal.

Friday, 16 September 2011

MVC

What the hell is a “Model-View-Controller”?

The Model-View-Controller Architecture, or MVC for short, is a way of programming that separates your application into three main parts:
  1. the Model
  2. the View
  3. and (you guessed it) the Controller
Basically, the separation of these three allows developers to differentiate three aspects of your application:
  1. Business Data (represented by the Model)
  2. Presentation Data (represented by the View)
  3. and Application Logic (represented by the Controller)
This allows for very rapid development – each aspect can be developed side by side by different developers at the same time. For example, we can have a designer working on the View and just allocating spaces where data will appear and at the same time, we can have a developer programming the Controller, who will just provide the View the data to be displayed. While all of this is being done, we can have another developer working on the Models, who will be in charge of retrieving data from the database and implementing the business-specific logic to them, and making sure that there are methods available for the Controller to be able to retrieve the data in different situations.
Using this also makes decoupling and modularization of your application very easy. Since each action on your application will have its own view-controller pair, this pair can be developed separately from another function with little or no setback.
The first time I read about MVC, I was a bit confused about the concept of three separated aspects of my application. I’ve read countless analogies trying to explain the MVC, and for me, one of the best analogies I’ve seen so far was from this article – Another way to think about MVC:
So, let’s imagine a bank.
The safe is the Database – this is where all the most important goodies are stored, and are nicely protected from the outside world.
Then we have the bankers or in programmatic terms the Models. The bankers are the only ones who have access to the safe (the DB). They are generally fat, old and lazy, which follows quite nicely with one of the rules of MVC: *fat models, skinny controllers*. We’ll see why and how this analogy applies a little later.
Now we’ve got our average bank workers, the gophers, the runners, the Controllers. Controllers or gophers do all the running around, that’s why they have to be fit and skinny. They take the loot or information from the bankers (the Models) and bring it to the bank customers the Views.
The bankers (Models) have been at the job for a while, therefore they make all the important decisions. Which brings us to another rule: *keep as much business logic in the model as possible*. The controllers, our average workers, should not be making such decisions, they ask the banker for details, get the info, and pass it on to the customer (the View). Hence, we continue to follow the rule of *fat models, skinny controllers*. The gophers do not make important decisions, but they cannot be plain dumb (thus a little business logic in the controller is OK). However, as soon as the gopher begins to think too much the banker gets upset and your bank (or you app) goes out of business. So again, always remember to offload as much business logic (or decision making) to the model.
Now, the bankers sure as hell aren’t going to talk to the customers (the View) directly, they are way too important in their cushy chairs for that. Thus another rule is followed: *Models should not talk to Views*. This communication between the banker and the customer (the Model and the View) is always handled by the gopher (the Controller).
(Yes, there are some exception to this rule for super VIP customers, but let’s stick to basics for the time being).
It also happens that a single worker (Controller) has to get information from more than one banker, and that’s perfectly acceptable. However, if the bankers are related (otherwise how else would they land such nice jobs?)… the bankers (Models) will communicate with each other first, and then pass cumulative information to their gopher, who will happily deliver it to the customer (View). So here’s another rule: *Related models provide information to the controller via their association (relation)*.

So what about our customer (the View)? Well, banks do make mistakes and the customer should be smart enough to balance their own account and make some decisions. In MVC terms we get another simple rule: *it’s quite alright for the views to contain some logic, which deals with the view or presentation*. Following our analogy, the customer will make sure not forget to wear pants while they go to the bank, but they are not going to tell the bankers how to process the transactions.

MVC in Web Development

Currently, a lot of web applications and Frameworks (Zend, CakePHP, Symfony, to name a few)  make use of the MVC Architecture. According to the Cookbook from CakePHP:
Why use MVC? Because it is a tried and true software design pattern that turns an application into a maintainable, modular, rapidly developed package. Crafting application tasks into separate models, views, and controllers makes your application very light on its feet. New features are easily added, and new faces on old features are a snap. The modular and separate design also allows developers and designers to work simultaneously, including the ability to rapidly prototype. Separation also allows developers to make changes in one part of the application without affecting others.
If you’ve never built an application this way, it takes some time getting used to, but we’re confident that once you’ve built your first application using CakePHP, you won’t want to do it any other way.
A diagram from ash.MVC, another PHP framework which uses the MVC architecture, illustrates the usual data-flow for a web application built with MVC in mind:
  1. First, the browser sends an HTTP request to the web application
  2. A dispatcher usually will get this HTTP request and determine which controller to be used. This dispatcher is usually called a Front Controller (not illustrated)
  3. The appropriate controller will receive it and from the data received, determine which model/s are needed, what data is required and what action is to be done to the data
  4. The model will be told by the controller and retrieve the data and implement any necessary actions. Then, it will return the results to the controller, successful or not.
  5. The controller, based on the results from the model, will then determine which view should be used and provide the view whatever data is to be published to the browser.
  6. The view will receive this data, implement any presentation logic to the data, and return it back to the controller.
  7. The controller will then return the results to the browser.
From this data-flow, we can see what role each part of the MVC plays in every request made.
On a standard web application, the MVC can be represented by the following:

Model

The model, in a web application, is usually composed of classes which represent data from the database and manipulative logic relative to the data. Let say you have a table called “guestbook_entries”. On your application, a Guestbook Model will represent this table, and be responsible for retrieving data from this table in many different situations – for example, on one page, you could probably be viewing all of the guestbook entries, so your model should have a “fetchAll” method somewhere. On another page, you can also be viewing one entry, so this model should also be responsible for finding and retrieving the data of a single record from the table as well. There could also be situations where you need the entries to be retrieved based on a particular post, a date, or even a set of records, limited to 5, starting on the 10th index of all records (read: pagination). All of this should be handled exclusively by the model.

View

The view is obviously the HTML/CSS aspect any web application. The view should never retrieve data from the Model, and should only be able to get this data based on what the controller gives it. This makes the view decoupled from the business logic, and makes it easier to change the logic with little or no effect on the view. This separation also allows for the application to reuse the view, making your application instantly template-friendly. Continuing from our example above, we can have a single view which is used to display a single guestbook entry. On a page which displays all of the entries, we can reuse the html file which displays one guestbook entry,and include it multiple times to show all of the entries.

Controller

The controller is the hub of all requests – it is usually the one who implements the actual application logic to the data-flow. It determines which model and view to use, based on the request that a user sends to it. It is usually represented by the different pages of a web application, like for example, the login page will usually have an Authentication controller, as would a registration page and a downloads page. From our example above, the guestbook page would have a controller, and this controller would be able to support requests for viewing a single guestbook entry and viewing all of these entries as well.

Note: Front Controller

Additionally, most MVC applications implement the use of a Front Controller. Basically, it’s a controller for all of the controllers. It determines which of the controllers is appropriate for specific pages and dispatches necessary information to them. For example, in our guestbook page, we send an HTTP request to view all of the guestbook entries to the application. This request will be received by the Front Controller, and based on the request data (POST, GET), it determines that it should be handled by the Guestbook controller. It will then send the data (the user, wanting to view all of the guestbook entries) to the controller.

Tuesday, 6 September 2011

State Management

State Management in ASP.NET


Web form pages are HTTP-Based, they are stateless, which means they don�t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost, therefore state management is really an issue in developing web applications

We could easily solve these problems in ASP with cookie, query string, application, session and so on. Now in ASP.NET, we still can use these functions, but they are richer and more powerful, so let�s dive into it.

Mainly there are two different ways to manage web page�s state: Client-side and Server-side.

1.Client-side state management :
There is no information maintained on the server between round trips. Information will be stored in the page or on the client�s computer.

A. Cookies.

A cookie is a small amount of data stored either in a text file on the client's file system or in-memory in the client browser session. Cookies are mainly used for tracking data settings. Let�s take an example: say we want to customize a welcome web page, when the user request the default web page, the application first to detect if the user has logined before, we can retrieve the user informatin from cookies:
[c#]
if (Request.Cookies[�username�]!=null)
lbMessage.text=�Dear �+Request.Cookies[�username�].Value+�, Welcome shopping here!�;
else
lbMessage.text=�Welcome shopping here!�;

If you want to store client�s information, you can use the following code:
[c#]
Response.Cookies[�username�].Value=username;

So next time when the user request the web page, you can easily recongnize the user again.
B. Hidden Field
A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you would like to store directly in the page. Hidden field stores a single variable in its value property and must be explicitly added it to the page.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.
[c#]
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to Hidden field
Hidden1.Value=�this is a test�;
//to retrieve a value
string str=Hidden1.Value;

Note: Keep in mind, in order to use hidden field, you have to use HTTP-Post method to post web page. Although its name is �Hidden�, its value is not hidden, you can see its value through �view source� function.
C. View State

Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don�t need to do anything about getting back the data of controls after posting page to the server.

Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.
[c#]
//to save information
ViewState.Add(�shape�,�circle�);
//to retrieve information
string shapes=ViewState[�shape�];

Note: Unlike Hidden Field, the values in ViewState are invisible when �view source�, they are compressed and encoded.

D. Query Strings
Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.
A URL with query strings may look like this:

http://www.examples.com/list.aspx?categoryid=1&productid=101

When list.aspx is being requested, the category and product information can be obtained by using the following codes:
[c#]
string categoryid, productid;
categoryid=Request.Params[�categoryid�];
productid=Request.Params[�productid�];

Note: you can only use HTTP-Get method to post the web page, or you will never get the value from query strings.

2. Server-side state management:
Information will be stored on the server, it has higher security but it can use more web server resources.
A. Aplication object
The Application object provides a mechanism for storing data that is accessible to all code running within the Web application, The ideal data to insert into application state variables is data that is shared by multiple sessions and does not change often.. And just because it is visible to the entire application, you need to used Lock and UnLock pair to avoid having conflit value.
[c#]
Application.Lock();
Application[�mydata�]=�mydata�;
Application.UnLock();
B. Session object

Session object can be used for storing session-specific information that needs to be maintained between server round trips and between requests for pages. Session object is per-client basis, which means different clients generate different session object.The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.

Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing URL-legal ASCII characters. SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide, and SessionID�s randomness makes it harder to guess the session ID of an existing session.
SessionIDs are communicated across client-server requests either by an HTTP cookie or a modified URL, depending on how you set the application's configuration settings. So how to set the session setting in application configuration? Ok, let�s go further to look at it.

Every web application must have a configuration file named web.config, it is a XML-Based file, there is a section name �sessionState�, the following is an example:

<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="20" />

�cookieless� option can be �true� or �false�. When it is �false�(default value), ASP.NET will use HTTP cookie to identify users. When it is �true�, ASP.NET will randomly generate a unique number and put it just right ahead of the requested file, this number is used to identify users, you can see it on the address bar of IE:

http://localhost/Management/(2yzakzez3eqxut45ukyzq3qp)/Default.aspx

Ok, it is further enough, let is go back to session object.
[c#]
//to store information
Session[�myname�]=�Mike�;
//to retrieve information
myname=Session[�myname�];
C. Database

Database enables you to store large amount of information pertaining to state in your Web application. Sometimes users continually query the database by using the unique ID, you can save it in the database for use across multiple request for the pages in your site.

Summary


ASP.NET has more functions and utilities than ASP to enable you to manage page state more efficient and effective. Choosing among the options will depand upon your application, you have to think about the following before making any choose:
  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or server?
  • Is the information sensitive?
  • What kind of performance experience are you expecting from your pages?
Client-side state management summary


Method
Use when
Cookies
You need to store small amounts of information on the client and security is not an issue.
View state
You need to store small amounts of information for a page that will post back to itself. Use of the ViewState property does supply semi-secure functionality.
Hidden fields
You need to store small amounts of information for a page that will post back to itself or another page, and security is not an issue.
Note   You can use a hidden field only on pages that are submitted to the server.
Query string
You are transferring small amounts of information from one page to another and security is not an issue.
Note   You can use query strings only if you are requesting the same page, or another page via a link.


Server-side state management summary


Method
Use when
Application state object
You are storing infrequently changed, application-scope information that is used by many users, and security is not an issue. Do not store large quantities of information in an application state object.
Session state object
You are storing short-lived information that is specific to an individual session, and security is an issue. Do not store large quantities of information in a session state object. Be aware that a session state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Database support
You are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.

Monday, 5 September 2011

sealed class

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one can not derive from it. Sealing a method means one can not override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing).

Sunday, 4 September 2011

c# Reserved Keywords

List of Reserved Keywords . If the specific keyword need  to be used as a variable . User @ before the keyword . Ex;  class can be used as @class



c# 4.0 Named and Optional Parameters


C# 4.0 Optional Parameters and Named Parameters

A few of the interesting features in C# 4.0 are Optional Parameters, Default Values, and Named Parameters. The idea is that the arguments on a method may have “Default Values” and therefore it is unnecessary to supply those arguments in a method call if you are willing to accept those default values. This helps in those cases when we overload methods several times to help alleviate the caller from having to provide all values in a method. With Optional Parameters and Default Values you can now set Default Values to arguments on a method:
static void Write(string name, string address, string city = “Sarasota) { ... }
In the method above we have assigned the city parameter a default value of “Sarasota”, which means it can now be used optionally by the caller of the method:
Write(”David Hayden”, “1234 Broad Street”); city not specified, accept default.
or I can override the value by passing in the city as usual: 
Write(“David Hayden“,“1234 Broad Street“,Tampa); // Overriding Default
Sometimes you may have multiple optional parameters:static void Write(string name, string address, string city = “Sarasota”, string state=“Florida) { ... }and the question becomes how do you specity a value for the state without specifying a value for the city? Named parameters, of course! We can now do the following:
Write(“David Hayden“,“1234 Broad Street“, state: “Hawaii); 

Saturday, 3 September 2011

c# 2.0 Partial Type

C# 2.0 introduces the concept of partial type definitions for classes, structs, and interfaces, as a means to break types in a program into multiple pieces to be stored in different source files for easier maintenance and development. This approach is particularly useful when the need arises to use nested types or provide interface implementation

Partial Type Attributes

Attributes on partial types are combined in an unspecified order so that they appear to all be defined on the given type

Example :

[Serializable]
Public Partial Class abc
{
int x;
}

[Dockable]
Public Partial Class abc
{
int y;
}
After Compliation the result would be

[Serializable,Dockable]
Public Partial Class abc
{
int x;
int y;
}

c# Generics

Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities

A Good example to know genrics importance  is Stack functionality which has push and pop functionality .
Before Generics we used a amorphous object datatype (under c# 1.1)
Object based Stack : Object is the canonical .NET base type, you can use the Object-based stack to hold any type of items, such as integers:
Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
int number = (int)stack.Pop();
Code block 1. An Object-based stack
public class Stack
{
   readonly int m_Size; 
   int m_StackPointer = 0;
   object[] m_Items; 
   public Stack():this(100)
   {}   
   public Stack(int size)
   {
      m_Size = size;
      m_Items = new object[m_Size];
   }
   public void Push(object item)
   {
      if(m_StackPointer >= m_Size) 
         throw new StackOverflowException();       
      m_Items[m_StackPointer] = item;
      m_StackPointer++;
   }
   public object Pop()
   {
      m_StackPointer--;
      if(m_StackPointer >= 0)
      {
         return m_Items[m_StackPointer];
      }
      else
      {
         m_StackPointer = 0;
         throw new InvalidOperationException("Cannot pop an empty stack");
      }
   }
}
However, there are two problems with Object-based solutions. The first issue is performance. When using value types, you have to box them in order to push and store them, and unbox the value types when popping them off the stack. Boxing and unboxing incurs a significant performance penalty in their own right, but it also increases the pressure on the managed heap, resulting in more garbage collections, which is not great for performance either. Even when using reference types instead of value types, there is still a performance penalty because you have to cast from an Object to the actual type you interact with and incur the casting cost:

Generics:
Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. You implement the server only once as a generic server, while at the same time you can declare and use it with any type. To do that, use the < and > brackets, enclosing a generic type parameter. For example, here is how you define and use a generic stack:
public class Stack<T>
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
int number = stack.Pop();

Friday, 2 September 2011

c#2.0 ,3.0,4.0 concepts chart

Following are the concepts that are added with new versions of c#

C# Concepts Chart