Introduction
In this article I am demonstrating the new features in C# 3.0. This demo is created as a simple C# console application to understand the new features of C# 3.0.
Background
I am a regular participant of Microsoft web casts and developer conferences. These web casts gives me a better understanding of new technologies. Also I was able to implement all these successfully in my projects. This article helps you understanding what are the new language features of C# 3.0
Using the code
Ok... Here we go…
If you don't have licenced Visual Studio 2008 installed on your machine, I would suggest you to download and inslall Visual Studio 2008 Express Edition ( Free).
This sample demo application starts with creating an Employee class. This has few properties in it. I would suggest you start doing it while going through this article.
public class Employees
{
#region AUTO IMPLEMENTED PROPERTIES
public string EmployeeName { get; set; }
public int EmployeeID { get; set; }
public string Department { get; set; }
#endregion
}
Here I have inroduced a language feature called Auto Implemented properies. You can notice that there is no private fields been declared for these properties. The compiler will creates the private backing fields for you.
Now we have created our Employee class. Lets create our main Program
class now.
public class Program
{
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
}
}
In the program main method, I have declared a List of Employees. I am using the method LoadEmployees
to get the Employee list. Normally in C#2.0 we will use the following code to create an Employee object and will add to the List.
private static List<employees /> LoadEmployees()
{
Employees emp1 = new Employees();
}
Here we need to set the values to the properies using the Employee objects emp1
. ie For example emp1.EmployeeName = "Albert";
Finally we will add the employee objects to an Employee List.
Now we will see the magic of C# 3.0
private static List<Employees> LoadEmployees()
{
List<Employees> employees = new List<Employees>()
{
new Employees{ EmployeeName="Albert", EmployeeID=1234,
Department="Software Testing"},
new Employees{EmployeeName="Justin", EmployeeID=1234,
Department="Development"}
};
}
Here I have introduced a new language feature called Object Initializers and Collection Initializers.
One more change…
Please note this line
List<Employees> employees = new List<Employees>() { ....
You can see the repetition of List<Employees>.
The type of List<Employees>
is mentioned twise. Lets see how can we avoid this in C# 3.0
I am rewriring the above line as
var employees = new List<Employees>() { ....
Ohh..whats that!..This is called Local variable Type Inference.
Don’t worry it will not break our type safety. You cannot assign any other types to employees as the compiler strongly typed the employees as the type assigned in its right side.
Ok…Now we can see different ways of querying this list of Employees using the LINQ feature of C# 3.0 We will go back to or Main method.
# 1.
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
var results = Enumerable.Where(employees, e => e.Department == "Development");
}
C# 3.0 introduced a new class called Enumerable
with some methods. This can be used on any IEnumerable types. Here I am using a method called Where. This method filters the collection by using some predicates. This predicates are created inline using another language feature known as “Lambda Expressions”. This simplifies the syntax of anonymous methods which we used in C# 2.0. This returns a list of Employees whose department is “Development”.
# 2
The Where method can be used as an extension method on the employees object. Yet another feature of C# 3.0 which we will cover later in this article.
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
var results = employees.Where(e => e.Department == "Development");
}
# 3.
One more improvement on this. Ie called a query expressions. I am re-writing the above code as
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
var query = from e in employees
where
e.Department == "Development"
select e;
}
I am not covering all the capabilities of LINQ here. We can use this query expressions to query against databases, XMLs, objects or any types of data that a third party can extend to work with LINQ. Lets try to print this result in a console.
foreach (var item in query)
{
Console.WriteLine("{0},{1},{2}", item.EmployeeName, item.EmployeeID,
item.Department);
}
Finally… we will see another feature called Extension Methods
Ok..What is Extension methods?
Extension methods are static method that can be invoked using the instance method syntax.
How can add an extension method?
namespace ExtensionMethodDemos
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public static class SampleStringExtensionClass
{
public static string SayHello(this string s)
{
return "Hello" + s;
}
}
}
Here I have a static class which has static method named SayHello.
Extension methods are defined as static methods but are called by using instance method syntax.
Note that the parameter to the extension method that is prefixed with the "this" keyword - this tells the compiler which type we are "extending" with our extension method.
Ok.. Let see how we can use in our code. I will take the same main program we used above.
namespace CSharp3._0Features
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExtensionMethodDemos;
public class Program
{
static void Main(string[] args)
{
string sampleString = " Albert";
string strExtended = sampleString.SayHello();
Console.WriteLine();
Console.WriteLine("****EXTENSION METHODS*******");
Console.WriteLine(strExtended);
Console.ReadLine();
}
}
}
Note that I have used the namespace ExtensionMethodDemos
whch we created earlier. I have created a variable of string type. This new string type is now having the method “SayHello()” as its extension method.
Points to Remember
If you do implement extension methods for a given type, remember the following two points:
- An extension method will never be called if it has the same signature as a method defined in the type.
- Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named
Extensions
, they will all be brought into scope by the using Extensions
; directive.
Reference: Microsoft MSDN, Microsoft MSDN WebCasts.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.