We haven’t even started adopting .NET 3.0 but Microsoft is at work and plans to ship the next Visual Studio and the .NET platform (most likely to be called 3.5) by the end of this year!*
The most significant addition to the languages this time is LINQ. It is a very cool technology that mixes concepts from my two favorite paradigms – object oriented and functional.
The syntax looks a lot like SQL and will be used a lot in this context but LINQ is not just for the data stored in the database, it is for any structured data.
One of the features introduced with LINQ is the var keyword which helps with declarations of complicated, nested generic types. If you use var, you don’t have to spell the type of the left hand side of the assignment, which is a great help (an example will follow shortly).
Some seem to think that this reduces type safety somehow. This is not true – var is just a syntactic sugar, it does not change the semantics of the language in any way. The example should make things clearer (tested with Orcas March 2007 CTP):
namespace LinqPlayground
{
class Data
{
private String _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
}
class Program
{
static void Main(string[] args)
{
List<data> data = new List<data> { new Data() { Name = "John", Id = 1 },
new Data() { Name = "Steven", Id = 2 },
new Data() { Name= "Scott", Id = 3}};
var dt = from d in data
where d.Name == "John"
select d.Id;
foreach (int i in dt)
Console.WriteLine("Id is {0}", i);
}
}
}
There is a “dumb” class Data that keeps some simple info about a person like name and id. I stuff 3 objects in a list, then select only the persons named “John”. It does look a lot like SQL, but it really isn’t (I won’t go into details in this post).
The interesting part is the emphasized line – note how I’m not specifying the type of the result of the query “from d in data…”. That’s because compiler can infer it for me, but in compile time, not in runtime.
I could have also written this line like this:
IEnumerable<int> dt = from d in data
where d.Name == "John"
select d.Id;
but not like this
IEnumerable<string> dt = from d in data
where d.Name == "John"
select d.Id;
as this gives you the compile time error: CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.Generic.IEnumerable<string>'. An explicit conversion exists (are you missing a cast?)
Don’t treat the var keyword as a hack – it simply helps you type (pun intended) less
but the types of the variables are still there.
*The release date of the (tentative name) Visual Studio 2007 is only a rumour at this point, I don’t have any inside info whatsoever.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5