.NET     Console.WriteLine( "All Things .NET" );
.NET Nerd Blog Home
6.01.2005

 
What's New in C# 2.0
My quick summary and comments on what's new in C# 2.0.
Mostly taken/summarized from MSDN online help.

Generics

Essentially C++ templates, but not as full-featured or complicated. Biggest difference: can't provide specializations for types or specific function overrides

// Declare the generic class
public class MyList<T>
{
....//
}
// Declare a list of type int
MyList<int> list1 = new MyList<int>();
// Declare a list of type string
MyList<string> list1 = new MyList<string>();
// Declare a list of type MyClass
MyList<MyClass> list1 = new MyList<MyClass>();

Iterators

Easy way to provide enumerator on your class.

// Iterator Example
public class DaysOfTheWeek
{
string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"};
public System.Collections.IEnumerator GetEnumerator()
{
foreach (string day in m_Days)
yield return day;
}
}
// Create an instance of the collection class
DaysOfTheWeek MyWeek = new DaysOfTheWeek();
// Iterate through it with foreach
foreach (string day in MyWeek)
Console.WriteLine(day);

Partial Classes


Allows you to split the definition of a class into multiple files. VS IDE does this to separate the generated code from the user code. Keeps things more clean.

Also can use it to separate large classes into multiple files to reduce competition for checked out files, etc.
// File: MyClassP1.cs
public partial class MyClass
{
public void method1()
{
}
}
// File: MyClassP2.cs
public partial class MyClass
{
public void method2()
{
}
}
Some rules:
- Essentially all the "pieces" of the partial type are merged at compile time.
- Can't use partial on delegates or enums.
- Nested types can be partial
- Attributes for partial types are merged at compile time
- Following are also merged: xml comments, interfaces, members
- All definitions of the partial class must contain partial

Nullable Types

int? x;
if (x != null)
Console.WriteLine(x.Value);
else
Console.WriteLine("Undefined");

The syntax T? is shorthand for System.Nullable<T>

HasValue property returns true if variable contains a value, false if it's null.

Anonymous Methods

Basically a way to pass a block of code as a parameter. Many times, this is when assigning a delegage.
// Create a handler for a click event
button1.Click += delegate { MessageBox.Show( "Click!") };


... and a few more...

-- Static Classes and Static Members
-- Accessor (get/set) accessibility (public, private, etc)
-- Friend assemblies (access to friend's private members) :)
-- #pragma warnings


Comments: Post a Comment

Powered by Blogger