Welcome to MSDN Blogs Sign in | Join | Help

Video: New Error Checking Feature in Visual Studio Service Pack 1

In this 12 minute video I talk with C# IDE PM DJ Park about a new feature in Visual Studio 2008 Service Pack 1 beta called Live Semantic Errors or Squiggles. This feature gives an increased level of live feedback on potential errors that might be found in your code. In the past, many of these errors would only surface after you tried to compile your code, but now you can see them interactively as you type code in the IDE. This feature should help developers become more productive by allowing them to find errors quickly.

You have the choice of either watching video correctly or downloading it as zip file:

 

DjAndCharlieSquiggles

Thanks to Beth Massi who filmed this video and produced a WMV file for us to share with the community.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 1 Comments
Filed under: , ,

Community Convergence XLV

Welcome to the 45th Community Convergence. I recently reached the two year mark here at Microsoft, and that means it is probably time for me to run some changes on my now familiar routines. In this post I'll begin that process by taking Community Convergence in a new direction.

In the past, this column has been used to report on the latest writings by members of the C# team and our immediate community. Overall, that has been a good strategy, but recent changes on the C# Dev Center have made me look for a new approach.

You may have noticed an increase in the feed aggregation technology being used on the Dev Center. As you probably know, an RSS feed contains a series of links to what are often disparate but related posts. Users can subscribe to a feed, and have the posts in the feed brought to their inbox, their browser, their desktop, their phone, their Zune, or some other location.

There are now several feeds on the Dev Center main page, two of which contain the kinds of posts that I have traditionally collected in Community Convergence:

  1. The Featured Content feed is one that I manage directly, and as such it most directly takes the place of the old style Community Convergence posts. It contains content that I think is interesting, focusing primarily on material created by the C# team. You can subscribe to this feed by clicking here. The content in this feed is now also sent directly to the default C# Start Page in Visual Studio. (From the VS menu, choose View | Other Windows | Start Page.)
  2. The section entitled C# Team and Community Blogs on the front page of the Dev Center is also a feed, but unfortunately you cannot subscribe directly to it at this time. Instead, you can read it on the front page of the Dev Center. This feed picks up on the tags from several blogs written both by C# team members and by prominent C# community members. When Matt Warren, Luca Bolognese, Eric Lippert, Jared Parsons or other teams members write a new blog post, it should show up in this list shortly after they publish. Several Microsoft MVPs, such as Bill Wagner and Mark Michaelis, can also mark posts to appear on this feed. We have recently added a few Developer Evangelists to this list as well.

A primary reason for adopting these feeds is to keep the content on the Dev Center fresh. We also want to allow you to subscribe to feeds so that the latest C# content can be delivered directly to your desktop.

There are other feeds on the Dev Center that you may have noticed. These include:

  • The Visual C# Code Gallery Samples: Code Gallery is a relatively new tool designed to replace the now defunct GotDotNet site. It allows team and community members to upload and download sample code and some related resources. You can find lots of interesting source code on this site, as well as other useful information such as white papers.
  • There is also a CodePlex feed on the front page of the Dev Center. It lists recent and popular projects hosted on the CodePlex site. On CodePlex you will find projects to which the community can contribute via check-in to an online source control tool, while Code Gallery is meant for projects that are developed by one person or group and simply posted for download. Both sites allow contributions from either Microsoft employees or community members, and both sites contain lots of source code.  A number of significant projects, such as IronPython, are released via CodePlex, and using this feed to keep an eye on what is happening on that site is always a good idea.

Finally, the feed tool that I use to maintain the Featured Content list can also be used to create custom lists. I've taken advantage of that functionality and created a list that will contain only content posted by the CSharp team. This means that only posts by people who are or who have been members of the CSharp team can appear on this list. I created that list this morning, so it is still fairly short, but you can click here to get started using it. I try to post only technical content in the Featured Content list, but I will use this list to link to any content produced by team members, whether it is technical or not. For instance, I'll add this Community Convergence post to that feed.

I should thank Beth Massi, John Molloy, Amar Shah and Kerby Kuykendall who did so much to drive the adoption of feeds and new tools like Code Gallery on the Dev Center. We all worked together on these projects but Beth, John and Kerby were always on the front lines manning the barricades.

Well, I'm done. I've written my first "new style" Community Convergence post. The idea for this particular post was worked out by John Boylan and myself, who is my contact at MSDN. I wouldn't have written it, however, if I didn't have some ideas for future posts. So watch this space to see if can actually come up with some ideas to keep moving this column in a new direction.

kick it on DotNetKicks.com

LINQ Farm: More on the LINQ Aggregate Operators

The LINQ aggregate operators allow you to perform simple math operations over the elements in a sequence. This post is designed to walk you through those operators, and give you an overview of how to use them. Table 1 shows a list of the 7 aggregate operators.

Note: All the samples shown in this post are found in the AggregateOperators program found on Code Gallery LINQ Farm.

Table 1: LINQ includes 7 aggregate operators designed to help you perform simple math operations. The definitions shown in this table are over-simplifications that give you a general sense of what you can do with a particular operator.

Count Count the elements in a sequence.
LongCount Count the elements in a very, very long sequence.
Sum Add the elements in a sequence
Min Find the smallest element in a sequence
Max Find the largest element in a sequence
Average Find the average value in a sequence
Aggregate Perform various binary operations on the elements in a sequence.

Except for the Aggregate operator itself, all of these operators have a simple, obvious default use. Several of these operators, do, however, have overloads that need a few sentences of explanation. I will show you one simple example of using the default behavior for the operators, and then dive a bit deeper with a second example that shows how to use at least one of the overloads.

The Count and LongCount Operators

The Count and LongCount operators return the number of elements in a sequence. The Count operator can find this number quickly by simply asking objects such as List<T> that support the ICollection<T> interface for the count. If that service is not available, then LINQ iterates over the items in a list to get the count.  The LongCount operator provides the same basic functionality, but allows you to work with an Int64. A simple example of using the Count operator is shown in Listing 1.

Listing 1: A simple example of using the Count and LongCount operators.

public void ShowCount()
{
    var list = Enumerable.Range(5, 12);
    Console.WriteLine(list.Count());
}

The overloads for Count and LongCount allow you to pass in a lambda expression that performs custom calculations from which LINQ can derive the count for a sequence. For instance, you can write code that returns the number of even numbers in a collection:

var list = Enumerable.Range(1, 25);
Console.WriteLine("Total Count: {0}, Count the even numbers: {1}",
    list.Count(), list.Count(n => n % 2 == 0));         

Our list consists of the numbers between 1 and 25. We call count once with the first version of the Count operator and get back the number 25.

The second overload of the Count operator takes a simple predicate. The declaration looks like this:

public static int Count<TSource>(this IEnumerable<TSource> source,
   Func<TSource, bool> predicate);

The predicate takes an integer and returns a bool specifying whether or not a particular value from the list passes a test. In our case, we simple ask whether or not the number is even. This computation will return the values 2, 4, 6 and so on up to 24, for a total of 12 elements.

The Min and Max Operators

The Min and Max operators are equally simple. Listings 2 and 3 show how it works. The first shows the behavior of the first overload of Min and Max, the second shows how to one of the other overloads to pose slightly more complex questions.

Listing 2: A simple example of using the Min and Max operators to determine and highest and lowest values in a sequence.

public void ShowMinMax()
{
    var list = Enumerable.Range(6, 10);
      Console.WriteLine("Min: {0}, Max: {1}", list.Min(), list.Max());
}

Our list consists of the number 6 through 15, so the code writes out the values 6 and 15 to the console.The C# source that implements Min and Max use the IComparable<T> or IComparable interfaces to perform the calculations. If you pass in a null argument you will get an ArgumentNullException.

For the more complex examples, I'm going to need a few rows of simple data, which I provide in Listing 3.

Listing 3: The following Item class and the GetItems method are used by most of the examples in this section of the text.

class Item
{
    public int Width { get; set; }
    public int Length { get; set; }

    public override string ToString()
    {
        return string.Format("Width: {0}, Length: {1}", Width, Length);
    }
}

private List<Item> GetItems()
{
    return new List<Item> 
    { 
       new Item { Length = 0, Width = 5 },
       new Item { Length = 1, Width = 6 },
       new Item { Length = 2, Width = 7 },
       new Item { Length = 3, Width = 8 },
       new Item { Length = 4, Width = 9 }
    };
}

There is no simple way to know maximum or minimum values from a list of Items. To find the largest Item do you choose the element with the greatest Length, the greatest Width, or some other value? To solve this problem the C# teams provided us with an overload of the Min and Max operators that take a delegate that we can use to select the proper value for the comparison:

public static int Max<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector);

Like nearly all the LINQ to Objects operators, Max is implemented as an extension method for the class IEnumerable<T>. It takes an extremely simple lambda that is passed an element from the enumeration and returns an integer. To see how this works, take a look at Listing 4.

Listing 4: A somewhat more complex use of Min and Max, demonstrating how to get minimum and maximum values for complex types with multiple fields.

List<Item> items = GetItems();
ShowList(items);
Console.WriteLine("MinLength: {0}, MaxLength: {1}", 
   items.Min(l => l.Length ), items.Max(l => l.Length));

As you can see, Min and Max both take a very simple delegate, which is implemented here as a lambda.

The lambda that is passed to Min looks like this: l => l.Length. This is lambda is so simple that it can be a bit confusing to people who are new to LINQ. Let's take one moment to be sure we understand what is happening.

We know that this LINQ operator must iterate over the sequence passed in to it, and we can assume that it passes each item it finds to the selector delegate. It then tests the result returned from selector, to see if it is the largest value returned. Without peeking at the real source code, it seems that Max might do something like the code in listing 5.

Listing 5: This method, which I created, mimics what occurs in the real Max method that ships with the C# 3.0 release.

public static class MyExtensions
{
    public static int Max<TSource>(this IEnumerable<TSource> source
      Func<TSource, int> selector)
    {
        int largest = int.MinValue;
        foreach (var item in source)
        {
            int nextItem = selector(item);
            if (nextItem > largest)
            {
                largest = nextItem;
            }
        }
        return largest;
    }

Assuming that we are working with a collection of Items, then selector, were it implemented as a standard method, would have to look something like this:

public int selector(Item item)
{
    return item.Length;
}

This method is semantically identical to the delegate we used in listing x: l => l.Length. It is very simple code that tells us which part of the Item class we are going to use to determine our max value.

It's all so simple that one feels a little like a character in Edgar Allan Poe's "The Purloined Letter:" the answer was hidden in plain sight. Once again we see that the biggest impediment to learning LINQ is the fear that it might be complicated. In practice, it is almost startlingly simple.

The Average Operator

Once one understands the pattern shown in our examination of the Min and Max operators, we find that it can be easily applied to most of the other Aggregate operators. Let’s look at the Average operator, which returns the average value from an enumeration.

For instance, one can find the average for a range of numbers like this:

var list = Enumerable.Range(0, 5);
  Console.WriteLine("Average: {0}", list.Average());

When run, this code tells us that the average of the numbers 0, 1, 2, 3, 4 is the value 2.

When working with a collection of Items, we face the same problem we had with Min and Max: How does one discover the average value for list of Items that define two properties called Length and Width? The answer, of course, is that proceed just as we did with Min and Max operators:

List<Item> items = GetItems();
double averageLength = items.Average(l => l.Length);
double averageWidth = items.Average(w => w.Width);
double averageValue = items.Average(v => v.Length + v.Width);
Console.WriteLine("AverageLength: {0}, AverageWidth: {1} AverageValue: {2}", averageLength, averageWidth, averageValue);

Again, we pass in very simple lambdas such as l => l.Length + l.Width or w => w.Width. Somewhere in the background code similar to what you see in the custom implementation for the Max operator found in listing 5.X. The code must iterate over the list, passing in each item to our lambda, which defines the value we want the Average operator to use in its calculations:

AverageLength: 2, AverageWidth: 7 AverageValue: 9

The Sum Operator

The Sum operator tallies the values in an enumeration. Consider the following simple example:

var list = Enumerable.Range(5, 3);
Console.WriteLine("List sum = {0}", list.Sum());

Our list consists of the numbers 5, 6 and 7. The Sum operator adds them together, producing the value 18.

working with a list of Items, the Sum operator faces the same problem we saw with the Min, Max and Average operators. It should come as no surprise that the solution is nearly identical:

var items = GetItems(); 
Console.WriteLine("Sum the lengths of the items: {0}", items.Sum(l => l.Length));

Here is the same pattern you saw with the Average, Min and Max operators: we pass in a simple lambda to help the Sum method know which part of an Item it should use as the operand when performing its simple addition. The result printed to the console is the value 10. If only the rest of our lives were quite this simple!

The Aggregate Operator

The Aggregate operator follows in the footsteps of the Sum operator, but it provides us with a few more options. Rather than taking a simple delegate like the other operators in this series, it asks for one similar to the lambda we worked with in a previous post:

public static T Aggregate<T>(this IEnumerable<T> source, Func<T, T, T> func);

We know what do to with delegates that looks like this. We could, for instance, create one that adds up a range of numbers:

var list = Enumerable.Range(5, 3);
Console.WriteLine("Aggregation: {0}", list.Aggregate((a, b) => (a + b)));

The aggregate operator gets passed the numbers 5, 6 and 7. The first time the lambda is called it gets passed 5 and 6, and adds them together to produce 11. The next time it is called it is passed the accumulated result of the previous calculation plus the next number in the series: (11 + 7) which yields 18. This is the same result we saw for the Sum operator in the previous section. This overload of the Aggregate operator is indeed very similar to the Sum operator, though it is more flexible, in that you can easily perform multiplication, division, subtraction and other operations instead of simple addition. For instance, this code performs multiplication, yielding the value 210:

list.Aggregate((a, b) => (a * b))

Before pushing on, I should backtrack a little and discuss two simple points that are often brought up when people talk about this first version of the Aggregate operator. If it is passed a list with one item, it returns that item. If it is passed a list with 0 items, it throws an InvalidOperationException.

A second overload of the Aggregate operator allows you to seed the process with an accumulator:

public static TAccumulate Aggregate<TSource, TAccumulate>(
    this IEnumerable<TSource> source, TAccumulate seed, 
    Func<TAccumulate, TSource, TAccumulate> func);

This is essentially the same operator as shown in the previous example, but now you can decide the starting point for the value that will be accumulated:

Console.WriteLine("Aggregation: {0}", list.Aggregate(0, (a, b) => (a + b)));

If we pass in a list with one item in it, say the number five, then the first time the lambda is called it would be passed the seed plus the sole item in the list:

(0 + 5)

The result, of course, is the number 5.

Suppose we pass in an accumulator of 0 plus the numbers 5, 6, 7.

var list = Enumerable.Range(5, 3);
Console.WriteLine("Aggregation: {0}", list.Aggregate(0, (a, b) => (a + b)));

In this case we would step through the following sequence:

0 + 5 = 5
5 + 6 = 11
11 + 7 = 18.

Again, we are doing essentially what we did with the Sum operator.

If you pass in a different seed, then you get a different result:

Console.WriteLine("Aggregation: {0}", list.Aggregate(3, (a, b) => (a + b)));

With a seed of 3, we get:

3 + 5 = 8
8 + 6 = 14
14 + 7 = 21

As mentioned earlier, the Aggregate operator allows us to perform not just addition, but multiplication, division or various other binary mathematical operations:

Console.WriteLine("Aggregation: {0}", list.Aggregate(1, (a, b) => (a * b)));

In this case the series looks like this:

1 * 5 = 5
5 * 6 = 30
30 * 7 = 210

Note that I passed in an accumulator equal to 1, so that we did not end up with the following series of operations:

0 * 5 = 0
0 * 6 = 0
0 * 7 = 0

In what I sometimes suspect might have been an excess of good spirits, the team added one final overload to the Aggregate operator:

public static TResult Aggregate<TSource, TAccumulate, TResult>(
                this IEnumerable<TSource> source, TAccumulate seed,
                Func<TAccumulate, TSource, TAccumulate> func,
                Func<TAccumulate, TResult> resultSelector);

This overload is nearly identical to the previous overload, but you are given one more, very simple, delegate that you can use to transform the result of your aggregation. For instance, consider this use of the Aggregate operator:

Console.WriteLine("Aggregation: {0}", list.Aggregate(0, (a, b) => (a + b),
    (a) => (string.Format("{0:C}", a))));

Please notice that the first two-thirds of this call mirror what we did earlier, and only the third parameter is new.

Suppose we pass in a sequence with the values 5, 6 and 7. As we've already seen, the process will begin by performing the following series of operations:

0 + 5 = 5
5 + 6 = 11
11 + 7 = 18

Once we have our result of 18, this number is passed to the last lambda in our call. It uses the string's Format method to transform it into a string in currency format:

$18.00

Like nearly everything in LINQ, this seems terribly complicated at first only to end up being reasonably simple. It is these kinds of simple operations, however, which provide us with the building blocks out of which we can safely create complex programs. This is what we mean when we apply the word elegant to a technology.

Note: All the samples shown in this post are found in the AggregateOperators program found on Code Gallery LINQ Farm.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 2 Comments
Filed under: , ,

LINQ Farm: More on Set Operators

This is a second post on the LINQ Set operators, the first being published while LINQ was still in beta. As mentioned in the previous post, there are four LINQ set operators: Union, Intersect, Distinct and Except. Like the other 49 LINQ operators, these methods are designed to allow you to query data which supports the IEnumerable<T> interface. Since all LINQ query expressions, and most LINQ queries, return IEnumerable<T>, these operators are designed to allow you to perform set operations on the results of a LINQ query.

In this post I give four highly simplified examples of how to use each of the operators, and then end with a more complex example that shows how the operators might be used in a real world setting.

Download the source code.

Union

The Union operator shows the unique items from two lists, as shown in listing 1.

Listing 1: The Show Union method displays the number 1, 2, 3, 4, 5 and 6.

public void ShowUnion()
{
    var listA = Enumerable.Range(1, 3);
    var listB = new List<int> { 3, 4, 5, 6 };

    var listC = listA.Union(listB);

    foreach (var item in listC)
    {
        Console.WriteLine(item);
    }
} 

Here two collections are joined together, but only the unique members of each list are retained.

Intersect

The Intersect operator shows the items that two lists have in common.

Listing 2: The ShowIntersect method displays the numbers 3 and 4

public void ShowIntersect()
{
    var listA = Enumerable.Range(1, 4);
    var listB = new List<int> { 3, 4, 5, 6 };

    var listC = listA.Intersect(listB);

    foreach (var item in listC)
    {
        Console.WriteLine(item);
    }
}       

Here to collections are joined together, and only the unique, shared members of each list are retained.

Distinct

The Distinct operator finds all the unique items in a list.

Listing 3: The ShowDistinct method displays the number 1, 2 and 3.

public void ShowDistinct() 
{
    var listA = new List<int> { 1, 2, 3, 3, 2, 1 };
    var listB = listA.Distinct();

    foreach (var item in listB)
    {
        Console.WriteLine(item);
    }
}

Except

The Except operator shows all the items in one list minus the items in a second list.

Listing 4: The ShowExcept method prints out the numbers 1, 2, 5, and 6

public void ShowExcept() 
{
    var listA = Enumerable.Range(1, 6);
    var listB = new List<int> { 3, 4 };

    var listC = listA.Except(listB);

    foreach (var item in listC)
    {
        Console.WriteLine(item);
    }
}

In the Context of LINQ

The type of code listed above is useful, but it might be helpful to see these same operators used in the context of a LINQ query expression. You can then see how they can be used to analyze the results of queries to better understand the data that is returned.

You probably know that there are two similar collections used to create lists. One is the generic List<T> collection and the other is the old-style collection called ArrayList. We can use set operators to help us better understand the difference between these two classes.

Here are two queries retrieving the methods from the List<int> class and the ArrayList class:

var queryList = from m in typeof(List<int>).GetMethods()
                where m.DeclaringType == typeof(List<int>)
                group m by m.Name into g
                select g.Key;

var queryArray = from m in typeof(ArrayList).GetMethods()
                 where m.DeclaringType == typeof(ArrayList)
                 group m by m.Name into g
                 select g.Key;

Here is code to retrieve the interesection of these two lists:

var listIntersect = queryList.Intersect(queryArray);

And here is code that displays the resulting sequence:

Console.WriteLine("Count: {0}", listIntersect.Count());
foreach (var item in listIntersect)
{
    Console.WriteLine(item);
}

Alternatively, you could write the query like this:

var queryList = (from m in typeof(List<int>).GetMethods()
                 where m.DeclaringType == typeof(List<int>)
                 group m by m.Name into g
                 select g.Key).Intersect(from m in typeof(ArrayList).GetMethods()
                                         where m.DeclaringType == typeof(ArrayList)
                                         group m by m.Name into g
                                         select g.Key);

In either case, the following list would be displayed:

get_Capacity
set_Capacity
get_Count
get_Item
set_Item
Add
AddRange
BinarySearch
Clear
Contains
CopyTo
GetEnumerator
GetRange
IndexOf
Insert
InsertRange
LastIndexOf
Remove
RemoveAt
RemoveRange
Reverse
Sort
ToArray

And here is how to see the items that the generic lists supports that are not part of the old style collection:

var listDifference = queryList.Except(listIntersect);

And here is the result of this query:

ConvertAll
AsReadOnly
Exists
Find
FindAll
FindIndex
FindLast
FindLastIndex
ForEach
RemoveAll
TrimExcess
TrueForAll

Now you have a list of the methods the two classes share in common, and a list showing what the new generic class has that is not part of the older collection. The LINQ set operators made it easy for you to discover this information.

Download the source code.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 2 Comments
Filed under: , ,

Video: Meet the C# Design Team with Anders Hejlsberg

Here is a video on Channel 9 with the members of the C# design team. The discussion covers C# 4.0, dynamic languages, concurrency and declarative programming,

Attendees include Anders Hejlsberg, Paul Vick, Scott Wiltamuth, Mads Torgersen, Matt Warren, Eric Lippert and Jim Hugunin.

Some of the topics discussed include:

  • When is the right time to use a dynamic language, when should one use a statically typed language? How can we begin to think about integrating C# with dynamic languages? What is the DLR and how can it be used from C#? LINQ and the dynamic construction of statically typed code.
  • How does one evolve a language without upsetting a user base? When do you build something into the language, and when do you just add a new API? If you add something into the language, how can you be sure you are betting on the right horse?
  • How does the design team work? The continuity of the process: meeting for 9 years, three times a week, in the same room. Design often happens in spurts. Keeping notes, a preserved history that reaches back 9 years.
  • Concurrency and purity, building isolation domains. Concurrency is very important, it is the heart of the current set of problems we are facing. Moore's law is still in effect: the number of transistors is continuing to double every 18 months, but the clock speed has stopped growing, it has literally stopped. So the way we get the more is more CPUs. It is hard problem, and that is why so many people have ignored it. How do you get developers to express their intent in a way that can scheduled across multiple processors? Should developers have to think about whether their code will run concurrently? Can we build programming models that are sufficiently close to what we know now, but which can automatically run concurrently? How can we guarantee that a given chunk of code will not have side effects? People think sequentially, how can we ask developers to think in a parallel style?
kick it on DotNetKicks.com
Posted by Charlie Calvert | 2 Comments
Filed under:

Future Focus: Searching and Navigating to Symbols

C++ PM Boris Jabes has added to our series of articles on features that are being considered for the next version of Visual Studio. In his post, Boris describes a proposed feature that will allow users to "find and navigate to a specific location in their solution." Boris explains that users can type in a string and the IDE will return a list of matching results drawn from the "symbol definitions and files in a solution." The feature is also designed to allow users to explore a solution by posing a potentially vaguely worded query and seeing a set of related results. This new search feature is not language specific, and hence can at least potentially be of use to all developers who use Visual Studio, regardless of whether they implement their programs in C++, C#, Visual Basic, or some other language.

Please take a look at this new Future Focus posting, and provide us with your feedback. Let us know if you think the feature is useful, if you think it is implemented properly, and if you have any suggestions as to how it can be improved. Future Focus articles are posted in Code Gallery, and space is provided there for you to comment on the proposed feature.

 

kick it on DotNetKicks.com

LINQ Farm: Lambdas

Lambdas are a simple technology with an intimidating name. They sound like they are going to be difficult to understand, but in practice prove to be relatively trivial.

LINQ has an almost inordinate need for its users to declare a large number of small, simple delegates. The architects of C# decided that forcing the users of LINQ to declare delegates using standard C# 2.0 delegate syntax was an overly verbose option. They wanted to find a shorter, more concise way to accomplish the same task.

The syntax they settled on looks like this:

Func<int, int, int> myLambda = (a, b) => (a + b);

This is a shorthand way of writing code which is semantically equivalent to the following:

public static int Add(int a, int b)
{
    return a + b;
}

Func<int, int, int> myDelegate = Add;

In the next few paragraphs I will compare these two ways of creating a delegate instance, and explain how they map back and forth.

It is obvious that the left hand side of the following two code fragments have the same meaning:

Func<int, int, int> myLambda = (a, b) => (a + b);
Func<int, int, int> myDelegate = Add;

But how can the right hand side be the same?

It turns out that that the expression on the right hand side of the first statement is a shorthand way of writing a method semantically equivalent to the Add method. Just to be clear, a lambda is not a reference to the Add method, it is second method that does the same thing as the Add method.

Here is the lambda:

(a, b) => (a + b);

And here is the Add method:

public static int Add(int a, int b)
{
    return a + b;
}

Here is the place in the Add method where we define the parameters it will take:

(int a, int b)

Here is the place in the lambda where we define the parameters that it will take:

(a, b)

Here is the place in the Add method where we define what it will return:

return a + b;

Here is the place in the lambda where we define what it will return:

(a + b)

As you can see, a lambda and a method do the same thing: they define a set of parameters and an executable body of code.

The type declarations for a lambda are resolved using a technique very similar to the one we employ for generic methods and generic delegates. To see how this works, look again at the full declaration for the lambda:

Func<int, int, int> myLambda = (a, b) => (a + b);

The generic delegate Func says that the method being implemented takes two integers as parameters, and returns an integer. The compiler takes this information and applies it to the lambda. Behind the scenes it resolves (a, b) to (int a, int b) and defines the function such that the body of the lambda (a + b) returns an integer. Thus we give the compiler enough information to convert our lambda into a method that performs the same action as the Add method.

The => symbol is called a lambda operator and is usually pronounced “goes to.” Thus the lambda above can be read as “a comma b goes to a plus b,” or “a and b goes to a plus b.”

Though you will rarely need to do so, you can explicitly declare the type of parameters to a lambda expression:

Func<int, int, int> f = (int a, int b) => (a + b);

For void functions that do not return a value, just use an empty set of parenthesis:

() => Console.WriteLine();

Lambdas have access to local variables:

public static void UseLocal()
{
    int n;
    Func<int> func = () => { n = 6; return n; };
    n = func();
    Console.WriteLine(n); // Outputs the number 6
}

You might be familiar with anonymous methods from C# 2.0. Semantically, anonymous methods and lambdas are identical, but the lambda syntax is easier to use. As a result, there is probably no reason for you to use anonymous methods in the future. Below is a lambda and anonymous method side by side:

Func<int, int, int> myLambda = (a, b) => (a + b);
Func<int, int, int> myAnonMethod = delegate(int a, int b)
{
    return a + b;
};

Both methods take two integers, add them together, and return the result. Commenting further on anonymous methods at this point would serve no purpose, since lambdas create the same result with less work.

In this post you have had a chance to look at lambdas. Their name is intimidating, and their syntax can be a bit confusing at first. Once you see beneath the facade however, this technology turns out to be relatively easy to master.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 29 Comments
Filed under: , ,

LINQ Farm: Extension Methods and Scoping

There are a few scoping rules that you must keep in mind when using extensions methods. Problems with scoping and extensions methods are rare, but when you encounter them they are quite vexing.

An instance method will always be called before an extension method. The runtime looks first for an instance method, if it finds an instance method with the right name and signature, it executes it and never looks for your extension method. The following code illustrates this problem:

using System;

namespace ConsoleApplication1
{
    public class MyClass
    {
        public void DoThis()
        {
            Console.WriteLine("MyClass.DoThis");
        }
    }


    public static class MyExtensions01
    {
        // Can never be called as if it were an instance method of MyClass.
        public static void DoThis(this MyClass myClass)
        {
            Console.WriteLine("MyExtensions01.DoThis");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.DoThis();                // Calls MyClass.DoThis
            MyExtensions01.DoThis(myClass);  // Calls MyExtensions01.DoThis
        }
    }
}

MyExtensions01.DoThis is a valid extension method for MyClass. However, it will never be called because MyClass.DoThis always takes precedence over it unless you explicitely call it as a static method of MyExtensions01.

In cases where you have two extension methods with the same name, an extension method in the current namespace will win out over one in another namespace. Ambiguity will become an issue, however, when you try to call two extension methods with the same name and signature in the same namespace, or in two different namespaces both used by the current namespace. See Listing 5 for an example of this problem.

The following code will not compile because the compiler finds the call to DoThat ambiguous:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ExtensionScope
{
    public class MyClass
    {
        public void DoThis()
        {
            Console.WriteLine("Do this");
        }
    }
}

namespace Extensions01
{
    using ExtensionScope;

    public static class MyExtensions01
    {
        // Can never be called
        public static void DoThis(this MyClass myClass)
        {
            Console.WriteLine("Do this");
        }

        public static void DoThat(this MyClass myClass)
        {
            Console.WriteLine("Do bop");
        }
    }
}

namespace Extensions02
{
    using ExtensionScope;

    public static class MyExtensions02
    {
        // Can never be called
        public static void DoThis(this MyClass myClass)
        {
            Console.WriteLine("Do this");
        }

        public static void DoThat(this MyClass myClass)
        {
            Console.WriteLine("Do bang");
        }
    }
}

namespace ExtensionScope
{
    using Extensions01;
    using Extensions02;

    class Program
    {
        static void Main(string[] args)
        {
            MyClass m = new MyClass();
            m.DoThat();
        }
    }
}

This program throws a compile time error because the compiler does not know if you want to MyExtionsions01.DoThat() or MyExtension02.DoThat(). There are two ways to resolve this error:

  • You could remove the using directive for either Extensions01 or Extensions02. In this case, that would be a fine resolution, but if there were other methods or classes in both Extensions01 and Extensions02 that you wanted to use, then this could become a painful, or even unacceptable, choice.
  • You could explicitly state which method you want to call using standard static syntax: MyExtensions01.DoThat(m).
  • You could move either MyExtensions02 or MyExtensions01 into the ExtensionScope namespace: 
namespace ExtensionScope
{
    public static class MyExtensions02
    {
        public static void DoThat(this MyClass myClass)
        {
            Console.WriteLine("MyExtensions02.DoThat");
        }
    }
}

This latter solution works so long as you have access to the source.

It should be clear that some of the issues discussed here can lead to trouble if you are not careful. In particular, you don't want to end up in a situation where forcing someone to remove a namespace results in them losing access to important functionality, nor do you want to force them to choose between functionality they desire and using your extensions.

It can also be a serious nuisance if you muddy a namespace with what many developers might consider superfluous methods. If you added 50 extension methods to the C# string class, then developers who just want to access the base functionality of that object would always have to contend with your methods, particularly when using IntelliSense.

To avoid or at least mitigate the seriousness of these problems, you should always place your extension methods in unique namespace separated from the rest of your code so that you can easily include or exclude the extension methods from a program. Listings 10 and 11 illustrate this technique.

Place your extensions in a separate file, and give them a unique namespace:

namespace MyCode
{
    public class MyCode
    {
        // Code omitted here
    }
   
}
namespace MyCode.Extensions
{
    public static class SpecialString
    {
        private static string[] stateCodes = 
                {"AL","AK","AZ","AR","CA","CO","CT","DE","FL",
                 "GA","HI","ID","IL","IN","IA","KS","KY","LA",
                 "ME","MD","MA","MI","MN","MS","MO","MT","NE",
                 "NV","NH","NJ","NM","NY","NC","ND","OH","OK",
                 "OR","PA","RI","SC","SD","TN","TX","UT","VT",
                 "VA","WA","WV","WI","WY"};

        public static bool IsState01(this string source)
        {
            if (source == null) return false;
            source = source.ToUpper(); 
            foreach (var item in stateCodes)
            {
                if (source == item)
                {
                    return true;
                }
            }
            return false;
        }

        public static bool IsState02(this string source)
        {
            return (source == null) ? false : stateCodes.Contains(source.ToUpper());
        }
    }
}

In this code I show you two alternative ways to implement the IsState extension method. The second, which uses LINQ, is probably easier to maintain. You can access the extension methods in a namespace MyCode.Extensions like this:

using System;
using MyCode;
using MyCode.Extensions;

namespace ConsoleApplication1
{
    class Program
    {            
        static void Main(string[] args)
        {
            MyCode myCode = new MyCode();
            // Use My Code here.
            string test = "WA";
            if (test.IsState02())
            {
                Console.WriteLine("{0} is a state", test);
            }
        }
    }
}

In this code your extension method is available and the code compiles. Comment out the third using statement and your extension method would not be available and the code would not compile. The developer would, however, still have access to the functionality found in the MyCode namespace. You could perhaps improve this technology by putting your extensions in their own assembly with its own namespace. You could then be sure that developers could choose to include or exclude the extra weight of your extension methods when they ship their code.

Though extension methods are particularly useful in LINQ, they are now a part of the language, and if used with caution, they can be useful. Placing them in their own namespace is a best practice that should help you get the most from this feature.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 9 Comments
Filed under: , ,

Cut Development Time: Use LINQ

When Microsoft employees talk about LINQ publicly, we haven't tended to emphasize how much time you can save by using it. This is perhaps because we don't want LINQ to be labeled as simply another RAD tool designed to save time. Nevertheless, it is becoming clear to me that shorter development cycles may be one of the first major benefits of LINQ to be widely recognized by the community.

I first began to notice the importance of this issue a month or two ago at a customer visit in San Diego. I asked if anyone at the company we were visiting was using LINQ. Only one person raised their hand. I asked him about his experience, and one of the first things he said was that he was able to get a lot of work done very quickly. DBA's at our session immediately chimed in with the usual objections about moving queries out of the database and into a codebase, and from there the discussion wandered off on a predictable tangent. Yet since then I've remembered that user's experience with rapid development, and the obvious enthusiasm he had for his subject.

The subject came up again during other stops in Southern California. The same point was raised by several developers I spoke with at Tech Ed, and again in a recent MSDN article by Dr. James McCaffrey. He said that LINQ reduced the time it took him to write test procedures by 50 percent. He added that LINQ to SQL made his test code "much shorter, much cleaner, and therefore easier to create, modify, and maintain."

Of course, LINQ has many other benefits. It provides a single unified query language that can be used across multiple data sources including SQL and XML. It is integrated into the C# language, allowing you to harness the power of .NET and the Visual Studio IDE when writing queries. It is both transformative and composable, allowing you to combine queries from multiple data sources in myriad ways. It uses a succinct and elegant declarative style of programming, and it is extensible so that you can run LINQ queries against any arbitrary data source. Yet sometimes it is simplest just to think of LINQ as a fast, elegant way to get a lot of work done quickly. In this day and age when we are all struggling to work with huge amounts of data, and to complete complex tasks in a short period of time, anything that will simplify our lives is welcome. LINQ is one of those things that just makes it easier to get work done quickly.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 14 Comments
Filed under: ,

WPF Farm: Simple WPF

It can be helpful to start from the beginning when working with new technologies. This post explains how to create a minimal WPF application that produces a single window with a gradient in it, as shown in Figure 1. The point of this exercise is to build the app from scratch, choosing File | New Project | Empty Project rather than File | New Project | WPF Application. The benefit of this exercise is to simply see what ingredients go into the production of a minimal WPF program.

 

AColorfulWpfWindow

Figure 1: A Simple WPF window with a gradient.

  1. Begin by choosing File | New Project | Empty Project from the Visual Studio 2008 menu.
  2. Choose Project | Add Class from the menu and add a new C# class called Program.
  3. Right click on the References section in the Solution Explorer and remove System.Data and System.Xml, but leave System. Add the following References as shown in Figure 2:
    1. PresentationCore
    2. PresentationFramework
    3. WindowBase
  4. Remove System.Linq and add the following to the program's using statements
    1. System.Windows
    2. System.Windows.Media
  5. Use the svm snippet to add a Main method to your code and use the ctor snippet to add a constructor to your code
    1. Put the [STAThread] attribute above the main method
  6. Fill in the main method and the constructor as shown in Figure 1
  7. Select from the menu Project | Project Properties and set the output type to Windows Application
  8. Have class Program derive from class Window
    1. class Program: Window
  9. Optionally right click on the editor and choose Organize Usings | Remove and Sort from the menu
  10. Press F5 to run the program. You should see the window shown in Figure 1.

 

References

Figure 2: The References section from the SimpleWpf project.

The complete source code to this project is shown in Listing 1. You can see that an Application object is created in the Main method, and that a few minimal fields of the window are filled out in the constructor. I also create a WPF LinearGradientBrush and set it as the Background for the window.

using System;
using System.Windows;
using System.Windows.Media;

namespace Project1
{
    class Program: Window
    {
        [STAThread]
        static void Main(string[] args)
        {
            Application application = new Application();
            application.Run(new Program());
        }

        public Program()
        {
            Width = 320;
            Height = 260;
            Title = "A Colorful Window";
            Background = new LinearGradientBrush(Colors.AliceBlue, Colors.Aquamarine,
                new Point(0, 0), new Point(1, 1));   
        }
    }
}

I should perhaps end by reminding you that the simplest way to create a WPF application in Visual Studio is to choose File | New Project | WPF Application. I have shown you this alternative technique simply because I hope you find it interesting or entertaining. It also illustrates that it is possible, though not necessarily recommended, to build WPF applications without using XAML.

The complete Source is on my LINQ Farm. Here is direct link to the download.

kick it on DotNetKicks.com
Posted by Charlie Calvert | 9 Comments
Filed under: ,

Visual Studio IDE Talk at Tech Ed 2008

I will be giving a talk at Tech Ed 2008, in Orlando Florida

  • Title: Microsoft Visual Studio 2008 IDE Tips and Tricks
  • Time: on Tuesday, June 3, at 10:30 AM.
  • Location: S320A
  • Talk Code: TLA321
  • Download Materials Related to he talk here.
  • Description: Harness the power of the 2008 IDE using new tips and tricks used by top Microsoft MVP developers and Microsoft employees. We look at new keyboard shortcuts, new options, the powerful "Quick Command" system, macros, tweaking IDE performance, and more that will make any developer using Visual Studio instantly more productive. The entire session is hands-on inside the IDE and applicable to any language, including Microsoft Visual Basic, Visual C#, and Visual C++. If you've been using Microsoft Visual Studio 2005 or have never touched Visual Studio, you're guaranteed to walk away a VS power user.

A repeat version of the talk will be given by Sara Ford on June 6, at 8:30 AM in room S230C. The code for the repeat session is TLA321R.

Posted by Charlie Calvert | 2 Comments
Filed under:

Color Schemes for the Visual Studio Editor

Developers with a bit of time on their hands have built some beautiful color schemes for the Visual Studio Editor. You can save download these settings files to your ...\Documents\Visual Studio 2008\Settings directory. You can then access them by choosing:

  • Tools | Import and Export Settings
  • Import Selected environment settings
  • No, just import new settings
    • (Consider saving the old settings the first time you do this.)
  • Select the new settings from the "My Settings" folder as shown in Figure 1
  • Choose next and import All Settings.
    • As shown in Figure 2, these files only have data from the Fonts and Colors sections of your VSettings file, so nothing else will be overwritten

 

Figure01

Figure 1: Selecting the new fonts and colors for the Visual Studio Editor

 

Figure02

Figure 2: You will only import new Fonts and Colors, the rest of your settings will be untouched

If you have color schemes you want to share with others, you need merely reverse the process, as follows:

  • Tools | Import and Export Settings
  • Export Selected Environment Settings
  • Unselect all settings, then drill down to choose the Fonts and Colors Settings (All Settings | Options | Environment | Fonts and Colors)
    • See Figure 3
  • Press Next and choose a name for your file
  • Click Finish

Figure03

The Color Schemes

Various people, such as

Scott Hanselman, and Adam, have called out these schemes in the past. Here are a few of my favorites:

Here are the default settings to get you back where you started:

Some of these settings files rely on custom fonts. Here is an explanation of how to install fonts on Vista, and here are a few of the more popular fonts for developers:

kick it on DotNetKicks.com
Posted by Charlie Calvert | 2 Comments
Filed under:

Where are the Visual Studio 2008 Keybinding Posters?

Download the posters in PDF format here:

  1. Visual C# 2008 Keybinding Reference Poster
  2. Visual Basic 2008 Keybinding Reference Poster
  3. Visual C++ 2008 Keybinding Reference Poster

Download the C# Keybindings in a spreadsheet.

Note that many of the keybindings stem from Visual Studio classes such Edit, Project, View, Window and Refactor. To see the complete list of methods for these classes, bring up the command window (Ctrl-W, A) and type File followed by a period. IntelliSense on all the methods for the File object will appear in the command window, just as if you were working with a C# class in the editor window. You can also see this classes in the find/command box on the toolbar (Ctrl + /). Inside the find/command box, type the the greater than symbol followed by the word Find and a period: >Find.

Here is a quick overview of the keybindings without the text that explains the purpose of each binding. You can also download a version of these bindings that will toggle hiding and showing the keybindings. You can use this feature to quiz yourself on the bindings. See the poster or the spreadsheet to retrieve the text explaining each keybinding: 

Visual C# 2008 Keybindings

Edit
Edit.CollapseTo-Definitions CTRL + M, O
Edit.ToggleAllOutlining CTRL + M, L
Edit.ToggleOutliningExpansion CTRL + M, M
Edit.StopOutlining CTRL + M, P
Edit.CommentSelection CTRL + K, C or CTRL + E, C
Edit.UncommentSelection CTRL + K, U or CTRL + E, U
Edit.FormatDocument CTRL + K, D or CTRL + E, D
Edit.FormatSelection CTRL + K, F or CTRL + E, F
Edit.InsertSnippet CTRL + K, X
Edit.SurroundWith CTRL + K, S
Edit.InvokeSnippetFromShortcut TAB
Edit.CycleClipboardRing CTRL + SHIFT + V
Edit.Replace CTRL + H
Edit.ReplaceInFiles CTRL + SHIFT + H
View.ShowSmartTag CTRL + . Or SHIFT + ALT + F10
File
File.NewProject CTRL + SHIFT + N
File.OpenProject CTRL + SHIFT + O
Project.AddClass SHIFT + ALT + C
Project.AddExistingItem SHIFT + ALT + A
Project.AddNewItem CTRL + SHIFT + A
Window.ShowEzMDIFileList CTRL + ALT