Search This Blog

2009-06-22

What is new in .NET 2.0

The following new features have been added to C# language with version 2.0 of .NET.

Generics
Iterators
Anonymous methods
Partial classes

generics :It is a programming language mechanism by which a single piece of code (function, object, interface, etc.) can manipulate many different data types.

Code Snippent:
class MyArrayList<ItemType>
{
private ItemType[] items = new ItemType[10];
private int count;
public void Add(ItemType item)
{
items[count++] = item;
}
public ItemType GetItem(int index)
{
return items[index];
}
}

To Call this method:
MyArrayList<int> iList = new MyArrayList();
MyArrayList<string> sList = new MyArrayList();

iList.Add(25);
int iValue = iList.GetItem(0);

sList.Add("Manab");
string sValue = sList.GetItem(0);

Using Methods:
Generic methods will allow you to pass one or more data types. An Example is given below.

public class MyClass
{
public ItemType MyMethod<ItemType>(ItemType item)
{
return item;
}
}

To Call the method
MyClass mc = new MyClass();
int i= mc.MyMethod<int>(32);
Response.Write(i.ToString());

C#Generics has the following advantages:
1.The Program becomes statically typed, so errors are discovered at compile-time.
2.No runtime casts are required and the program runs faster.
3.Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.

iterator : An iterator is an object that allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation.
foreach Loops Based on an Enumerator Pattern

// Implementation
ArrayList list = new ArrayList();
// ...
foreach(object obj in list)
{
DoSomething(obj);
}
// Translation through compiler
Enumerator e = list.GetEnumerator();
while(e.MoveNext())
{
object obj = e.Current;
DoSomething(obj);
}

Anonymous Methods:Anonymous methods let you define methods, usually delegates, inline with the declaration of the event.

You can replace this code:

button.Click += new EventHandler (this.bClick);
// elsewhere
private void bClick (sender, e)
{
MessageBox.Show ("click");
}

with the code given below:

button.Click +=new EventHandler (object sender, EventArgs e)
{
MessageBox.Show ("click");
}

Partial Classes:This feature allows you to split a particular class into two or more separate files. For this purpose, every part of the class is marked with the new modifier partial. The compiler looks for the marked parts and merges them into one complete implementation. You'll see no difference at run time. The assembly of the code parts requires all elements be in the same project and a parallel compilation. In addition, the classes have to match logically and must be identical regarding their modifiers, supported interfaces, and so on.

using System;
public partial class Foo
{
public void SomeMethod()
{
}
}
// foo2.cs
using System;
public partial class Foo
{
public void SomeOtherMethod()
{
}
}

No comments: