New features in C# for the .NET SDK 2.0 (corresponding to the 3rd edition of the ECMA-334 standard) are:
- Partial classes allow class implementation across more than one file. This permits breaking down very large classes, or is useful if some parts of a class are automatically generated.
file1.cs:
public partial class MyClass
{
public MyClass()
{
// implementation
}
}
file2.cs:
public partial class MyClass
{
public SomeMethod()
{
// implementation
}
}
- Generics or parameterized types. This is a .NET 2.0 feature supported by C#. Unlike C++ templates, .NET parameterized types are instantiated at runtime rather than by the compiler; hence they can be cross-language whereas C++ templates cannot. They support some features not supported directly by C++ templates such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information.
- Static classes that cannot be instantiated, and that only allow static members. This is similar to the concept of module in many procedural languages.
- A new form of iterator that provides generator functionality, using a yield return construct similar to yield in Python.
// Method that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable<int> GetEven(IEnumerable<int> numbers)
{
foreach (int i in numbers)
{
if (i % 2 == 0) yield return i;
}
}
- Anonymous delegates providing closure functionality.
public void Foo(object parameter)
{
// ... ThreadPool.QueueUserWorkItem(delegate
{
// anonymous delegates have full access to local variables of the enclosing method
if (parameter == ...)
{ // ...
} // ...
});
}
|