Wednesday, August 6, 2008

C# programming overview

Overview of C# 3.0

The main goal of C# 3.0 is to simplify working with data and make it possible to access relational data sources (database) in much simpler ways. In C# 3.0, this is implemented in an extensible way, not by simply adding several special-purpose constructs. Thanks to the new language constructs, it is possible to write statements like the following:

var query = from c in db.Customers                where City == "London"               orderby c.ContactName;               select new { CustomerID, ContactName };

This statement looks like an SQL query. This is achieved thanks to query operators (FROMWHERESELECTORDERBY and some others) that were added to the language. These operators are syntactic sugar that simplify writing of queries, but are mapped to underlying functions that perform projection, filtering or sorting. These functions are called SelectWhereOrderBy. For example, to perform filtering, the Where function needs to take another function as a parameter. Passing functions as a parameter to other functions is possible using new a language feature called lambda expressions. This is similar to the lambda functions known from many functional languages. You can also see that the query returns only CustomerID and ContactName from the more complex Customer structure. It is not required to explicitly declare a new class with only these two members because C# 3.0 allows developers to use anonymous types. It is also not required to declare the type of query variable because type inference automatically deduces the type when the var keyword is used.

Cω and integration of data access

The original idea of integrating data access into the general purpose programming language first appeared in the Cω research project at Microsoft Research. The data access possibilities integrated in Cω include working with databases and structured XML data. The LINQ project is mostly based on Cω; however, there are some differences. The features that can be found in both C# 3.0 and Cω include anonymous types (these are not limited to local scope in Cω), local type inference and query operators. One concept that wasn't available in Cω is extensibility through expression trees. In Cω, you couldn't write your own implementation of data source that would execute queries over anything other than in-memory data. The following demonstration shows how working with databases in Cω looks; it is very similar to the previous example written in C# 3.0:

query = select CustomerID, ContactName            from db.Customers            where City == "London"           order by ContactName;

The Cω project will be mentioned later in other sections because some of the features that are available in C# and were originally implemented in Cω are more powerful in Cω. It is therefore interesting to see this generalization.

No comments: