Welcome to MSDN Blogs Sign in | Join | Help

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 | 10 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 compiler 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.

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. You cannot, however, have two extension methods with the same name and signature in the same namespace, or in two different namespace 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 ConsoleApplication14
{
    public class MyClass
    {
        public void DoThis()
        {
            Console.WriteLine("Do this");
        }
    }
}

namespace Bop
{
    using ConsoleApplication14;

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

namespace Bang
{
    using ConsoleApplication14;

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

namespace ConsoleApplication14
{
    using Bop;
    using Bang;

    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 Bop or Bang. In this case, that would be a fine resolution, but if there were other methods or classes in both Bob and Bang 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 ConsoleApplication14 namespace:

 

namespace ConsoleApplication14
{
    using ConsoleApplication14;

    public static class MyExtensions02
    {
        public static void DoThat(this MyClass myClass)
        {
            Console.WriteLine("Doing this in an extension method Bang");
        }
    }
}

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
    {
        public static bool IsState(this string source)
        {
            string[] stateCodes = 
                {"AL","AK","AZ","AR","CA","CO","CT","DE","DC",
                 "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"};
                        foreach (var item in stateCodes)
            {
                if (source.ToUpper().Equals(item))
                {
                    return true;
                }
            }
            return false;
        }
    }
}

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.IsState())
            {
                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 | 8 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 + DOWN ARROW
Edit.OpenFile CTRL + O
Intellisense
Edit.CompleteWord CTRL + SPACE or CTRL + K, W
Edit.ListMembers CTRL + J or CTRL + K, L
Edit.QuickInfo CTRL + K, I
Edit.ParameterInfo CTRL + SHIFT + SPACE or CTRL K, P
Make Completion List Transparent CTRL
Navigation
Edit.FindAllReferences SHIFT + F12 or CTRL + K, R
Edit.GoToBrace CTRL + ]
Edit.GoToDefinition F12
Edit.GoToNextLocation F8
Edit.IncrementalSearch CTRL + I
View.ClassViewGo-ToSearch, Combo CTRL + K, CTRL + V
View.ForwardBrowseContext CTRL + SHIFT + 7
View.PopBrowseContext CTRL + SHIFT + 8
View.NavigateBackward CTRL + MINUS SIGN (-)
View.NavigateForward CTRL + SHIFT + MINUS SIGN (-)
Edit.FindInFiles CTRL + SHIFT + F
Edit.FindSymbol ALT + F12
View.ViewCode F7
View.ViewDesigner SHIFT + F7
View.ViewMarkup SHIFT + F7
Window.MoveToNavigationBar CTRL + F2
Edit.Find CTRL + F
Edit.GoTo CTRL + G
Edit.GoToFindCombo CTRL + /
Window
View.ClassView CTRL + W, C
View.CodeDefinitionWindow CTRL + W, D
View.Command-Window CTRL + W, A
View.ErrorList CTRL + W, E
View.ObjectBrowser CTRL + W, J
View.Output CTRL + W, O
View.PropertiesWindow CTRL + W, P
View.SolutionExplorer CTRL + W, S
View.TaskList CTRL + W, T
View.Toolbox CTRL + W, X
View.ServerExplorer CTRL + W, L
Window.CloseToolWindow SHIFT + ESC
Data.ShowDataSources SHIFT + ALT + D
Window.CloseDocument, Window CTRL + F4
Window.NextDocument, WindowNav CTRL + TAB
Refactor
Refactor.EncapsulateField CTRL + R, E
Refactor.ExtractInterface CTRL + R, I
Refactor.ExtractMethod CTRL + R, M
Refactor.PromoteLocalVariabletoParameter CTRL + R, P
Refactor.RemoveParameters CTRL + R, V
Refactor.Rename CTRL + R, R or F2
Refactor.ReorderParameters CTRL + R, O
Debugging
Debug.Autos CTRL + D, A
Debug.CallStack CTRL + D, C
Debug.Immediate CTRL + D, I
Debug.Locals CTRL + D, L
Debug.QuickWatch CTRL + D, Q
Debug.Start F5
Debug.StartWithoutDebugging CTRL + F5
Debug.StepInto F11
Debug.StepOut SHIFT + F11
Debug.StepOver F10
Debug.StopDebugging SHIFT + F5
Debug.ToggleBreakpoint F9
Debug.Watch CTRL + D, W
Debug.EnableBreakpoint CTRL + F9
Make Datatip Transparent [CTRL]
Build
Build.BuildSolution F6 or CTRL + SHIFT + B
Build.BuildSelection SHIFT + F6

 

kick it on DotNetKicks.com

Posted by Charlie Calvert | 6 Comments
Filed under:

VCS Team Links for May 22, 2008

Rather than place the links to the most recent C# team content directly in Community Convergence, I have moved them here. This posts covers the last few weeks of posts from the C#, F# and related teams.

From the C# Team

Eric Lippert

Matt Warren

Kirill Osenkov

Charlie Calvert

 

From the F# Team

Luke Hoban

Other C# Related Content

Dinesh Kulkarni

Keith Farmer

Japanese Content

Mitsu

Scott Guthrie

Wriju

Scott Hanselman

Brad Abrams

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

Community Convergence XLIV

Welcome to the forty-fourth Community Convergence. I want to remind every one that the C#, VB and dynamic language teams are still hiring. If you are an expert manager, developer or test engineer, please look at our listings and see if there is a place where you might belong. This is an excellent opportunity to participate in a first rate development process and to meet and work with some of the best developers in the world.

Tech Ed 2008 is fast approaching. This year it will be held in Orlando, Florida and divided into two sections. The Developer sessions will be held June 3-6, and the IT Professionals will gather June 10-13. Bill Gates will give the keynote at the developer conference, and there will be 16 tracks for you to explore. Several C# team members will be giving talks, as explained below.

I'm sure everyone knows that the betas for Visual Studio 2008 SP1 and .NET 3.5 SP1 have been released. Please download these bits and gives us feedback outlining how you think they look. Here are are posts by Brad Abrams and Scott Guthrie that can help get you up speed on these new bits, and here is the download for the betas.

Other news includes Keith Farmer's departure from Microsoft. Keith is a developer, but he has been a hard working and steady contributor to the community. He has been very active on the forums, in his blog, and across the net. We will miss him.

Finally, I'm going to try changing the format of Community Convergence for several reasons. First, the MSDN team has asked me to shorten these posts to fit in better with their new look and feel for the site. Secondly, we've had great success with our Visual C# Team and Community Blogs section, and feel that some of my listings are also appearing there. Thirdly, it is simply time for a change, and this will force me to try to become a bit more creative with my use of this space. As a result, I will try, as an experiment, moving the team links to a separate page, and use this space for important announcements, team gossip, and highlighting news.

See the most recent C# Team and Community Blog Links.

Tech Ed 2008 Talks by the C# Team

  • Meet the Microsoft Visual C# Team
    • Speakers: Charlie Calvert, Mads Torgersen, Alex Turner, Karen Liu, Eric Maino, others....
    • 6/5/2008 4:30PM-5:45PM (Blue Theater 2)
    • Join members of the Visual C# team as we discuss Microsoft Visual Studio 2008 and our plans for the next release of Visual Studio. This is a good opportunity to get to know team members, to ask questions, give suggestions, and ask for guidance. Come prepared to chat, to listen, to ask questions, and to laugh.
  • How LINQ Works: A Deep Dive into the Implementation of LINQ
    • Speaker: Alex Turner
    • Level: 400 - Expert
    • Friday, June 6 1:00 PM - 2:15 PM, S320 A
    • Want to know what really happens when you execute your favorite LINQ queries? Curious how the same query expression can target either in-memory data or relational data? In this 400-level talk, Alex Turner, the C# Compiler Program Manager, uses Reflector and other tools to reveal exactly how the compiler translates LINQ query expressions. Gain a deeper understanding of LINQ’s functional roots as we see how lambda expressions and iterator methods enable LINQ to Objects' elegant syntax. Then find out what's the same and what's radically different as we explore LINQ to SQL and the expression trees that make it tick.
  • Best Practices with the Microsoft Visual C# 3.0 Language Features (Repeats on 6/6)
    • Speaker: Mads Torgersen
    • Tuesday, June 3 3:00 PM - 4:15 PM, S320 E
    • Friday, June 6 8:30 AM - 9:45 AM, S330 A 
    • Visual C# 3.0 introduces a number of new language features such as query expressions, lambda expressions, extension methods, automatically implemented properties, local type inference and more. These are all features that can really improve the quality of your code. They also give you new ways of doing things wrong. This talk focuses on both the good and the bad: how to use and how not to use the new features of C#. Each feature is introduced with a small example, and you should be able to follow the talk even if you are not already familiar with the new language constructs.
  • Microsoft Visual C# IDE Tips and Tricks
    • Speaker: Karen Liu
    • Thursday, June 5 10:15 AM - 11:30 AM, S220 E
    • In this demo-focused session, we look at a number of ways to make you more productive in the Visual C# IDE as you move through the development lifecycle—whether you're trying to come up to speed with an unfamiliar code base, performing a refactoring to help keep your code clean, writing in new pieces of business logic, or debugging through a problem. These are the tips from the C# team itself—features from Microsoft Visual Studio 2005, 2008 and out-of-box solutions that we use and love telling people about for making tasks easier.
  • Microsoft Visual Studio 2008 IDE Tips and Tricks (Repeats on 6/6)
    • Speaker: Charlie Calvert (repeat by Sara Ford)
    • Tuesday, 6/3/2008 10:30AM-11:45AM (S320 A) - Charlie
    • Friday, June 6 8:30 AM - 9:45 AM, S230 C - Sara
    • 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.

kick it on DotNetKicks.com

Give Us Your Feedback: Take the Visual Studio Survey

A new Visual Studio survey has been created and we would like your feedback. This survey focuses on learning more about the types of applications you are creating, which tools and technologies you are using, and how we can improve our content and code examples to better meet your needs. There are also questions about how you access online help, and some questions about the .NET Framework docs.

The survey is located here:   Visual Studio and .NET Framework Developer Documentation Survey

If you have time to take the survey and give us feedback, we will appreciate it.

kick it on DotNetKicks.com

Build Games for the Zune: XNA Game Studio 3.0 Tech Preview

If you want to program games for the Zune you'll need either Visual Studio C# 2008 Express or Visual Studio Standard Edition or higher with C# installed. This CTP works only for Zune and Windows, and does not support XBox 360. However, it runs side by side with Visual Studio 2005 and XNA 2.0, which does support XBox 360. The CTP does not work in 64 bit at this time.

You might also be interested in this starter kit, which is a role playing game for the XNA studio platform.

More details:

  • Get the 3.0 CTP (VS 2008) or the 2.0 CTP (VS 2005)
  • Read the announcement here.
  • Tour the web site
  • You can ask questions and report problems here.
kick it on DotNetKicks.com
Posted by Charlie Calvert | 1 Comments
Filed under: ,

Charlie Speaking in Southern California

I will be presenting on C# and LINQ three times in Southern California next week at a series of user group meetings. The events will be held in the San Diego and the Los Angeles area. Lisa Feigenbaum will be flying down from Redmond with me, and she will do VB presentations at the same set of meetings.

The schedule is as follows:

I will be talking on C# 3.0 Best Practices and LINQ:

C# 3.0 introduces a number of new language features such as query expressions, lambda expressions, extension methods, automatically implemented properties, local type inference and more. These are all features that can improve the quality of your code. They also provide new opportunities for making mistakes This talk focuses on both the good and the bad: how to use and how not to use the new features of C#. Each feature will be introduced with a small example, and you should be able to follow the talk even if you are not already familiar with the new language constructs. The talk will also explore the theoretical underpinnings of LINQ.

Lisa will be speaking on Visual Basic 2008 IDE Tips and Tricks:

In this talk, we’ll show how to turn yourself into a Visual Studio 2008 guru with the new language and IDE features. Tips and tricks will include how to maximize your VB IntelliSense experience, leverage Refactoring features, and improve the performance of your query and XML code. We’ll explore integrated XML, and show how to navigate XML gotchas and express what you wish in fewer lines of code. With respect to LINQ we’ll go deep into best practices, pitfalls to avoid, and answers to most frequently asked questions

Tuesday Night:

Wednesday Night

  • Microsoft
  • Three Park Plaza, Suite 1800
  • Irvine, CA 92614

Thursday Night

  • American Honda Motors
  • Bldg 100, # 100-1E-13
  • 1919 Torrance Blvd
  • Torrance, CA 90501

 

Source and deck from the talk.

 

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

Managed Languages Team is Hiring

The C#, VB, F#, Python and Ruby teams are looking for program managers, developers and testers who want to come work at Microsoft. The languages I've listed are among the most popular in use today, and Microsoft is in the forefront of the innovations that are driving the future of computer language development. Though not all our plans public at this time, I can say that we are involved in developing many exciting new technologies. The C# team has just finished shipping LINQ, which is provides developers with a powerful new technology for querying data. F# is exciting new language which will ship in the near future. There is surge of energy in the development world about dynamic languages such as Ruby and Python, and of course VB is one of the most popular languages in the world, as it has been for many years and will continue to be in the future.

Perhaps the best reason to come work at Microsoft is the chance to become friends with other highly skilled engineers. Some of the most brilliant developers in the world work at Microsoft, and the general level of expertise inside the language buildings is very high. The chance to talk with the best engineers and to develop and drive these technologies represents a unique opportunity for developers to enhance their skills, learn about computer science, and get insights into the future of computing.

Here are few of the openings available. I will look to post more openings here as I learn about them:

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

LINQFarm: Understanding IEnumerable<T>, Part I

The IEnumerable<T> interface is a key part of LINQ to Objects and binds many of its different features together into a whole. This series of posts explains IEnumerable<T> and the role it plays in LINQ to Objects. If you hear people talking about IEnumerable<T>, and sometimes wished you better understood its significance, then you should find this text helpful.

Collections and IEnumerable<T>

Though LINQ to Objects can be used to query several C# types, it cannot be used against all your in-process data sources. Those that can be queried all support the IEnumerable<T> interface. These include the generic collections found in the System.Collections.Generic namespace. The commonly used types found in this namespace include List<T>, Stack<T>, LinkedList<T>, Queue<T>, Dictionary<TKey, Value> and Hashset<T>.

All of the collections in the System.Collections.Generic namespace support the IEnumerable<T> interface. Here, for instance, is the declaration for List<T>:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable

You will find IEnumerable<T> listed for all the other generic collections. It is no coincidence that these collections support IEnumerable<T>. Their implementation of this interface makes it possible to query them using LINQ to Objects.

LINQ to Objects and IEnumerable<T>

Consider the following simple LINQ query:

List<int> list = new List<int> { 1, 3, 2 };
// The LINQ Query expression
var query = from num in list
            where num < 3
            select num;
foreach (var item in query)
{
    Console.WriteLine(item);
}

The type IEnumerable<T> plays two key roles in this code.

  • The query expression has a data source called list which implements IEnumerable<T>. 
  • The query expression returns an instance of IEnumberable<T>.

Every LINQ to Objects query expression, including the one shown above, will begin with a line of this type:

from x in y

In each case, the data source represented by the variable y must support the IEnumerable<T> interface. As you have already seen, the list of integers shown in this example supports that interface.

The same query shown here could also be written as follows:

IEnumerable<int> query = from num in list
                         where num < 3
                         select num;

This code makes explicit the type of the variable returned by this query. As you can see, it is of type IEnumerable<int>. In practice, you will find that most LINQ to Objects queries return IEnumerable<T>, for some type T. The only exceptions are those that call a LINQ query operator that return a simple type, such as Count():

int number = (from num in list
              where num < 3
              select num).Count();

In this case the query returns an integer specifying the number of items in the list created by this query. LINQ queries that return a simple type like this are an exception to the rule that LINQ to Objects queries operate on class that implement IEnumerable<T> and return an instance that supports IEnumerable<T>.

Composable

The fact that LINQ to Objects queries both take and return IEnumerable<T> enables a key feature of LINQ called composability. Because LINQ queries are composable you can usually pass the result of one LINQ query to another LINQ query. This allows you to compose a series of queries that work together to achieve a single end:

List<int> list = new List<int> { 1, 3, 2 };

var query1 = from num in list
             where num < 3
             select num;

var query2 = from num in query1
             where num > 1
             select num;

var query3 = from num1 in query1
             from num2 in query2
             select num1 + num2;

Here the results of the first query are used as the data source for the second query, and the results of the first two queries are both used as data sources for the third query. If you print out the results of query3 with a foreach loop you get the numbers 3 and 4. Though it is not important to the current subject matter, you might have fun playing with the code to understand why these values are returned.

Summary

By now it should be clear to you that IEnumerable<T> plays a central role in LINQ to Objects. A typical LINQ to Objects query expression not only takes a class that implements IEnumerable<T> as its data source, but it also returns an instance of this same type. The fact that it takes and returns the same type enables a feature called composability.

The next logical question would be to ask why this type plays such a key role in LINQ to Objects. One simple answer would be that the creators of LINQ decided that it should be so, and hence it is so. But one can still ask why they picked this particular type. What is it about IEnumerable<T> that makes it a useful data source and return type for LINQ to Objects queries? The answer to that question will be found in the second part of this series of articles.

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

Community Convergence XLIII

Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by the 2008 MVP Summit. During that annual event about 150 C# MVPs and many MVPs from other disciplines descend on Redmond for a technical summit accompanied by fun and games at local restaurants and hotels. Below I include a summary of the event by Jeremy D. Miller. One of the highlights of the event is a day in which the C# MVPs hear directly from the team about our plans for the future.

Other recent news includes the release of the Visual LINQ Query Builder, a tool for helping developers compose LINQ queries. Mitsu Furuta and others have been working hard on this project, and it is great to finally see it available for download. It is a useful programming tool for all LINQ developers, and especially for those who are new to LINQ and want some help learning the syntax.

From the C# Team

Luca Bolognese

Kirill Osenkov

Charlie Calvert

From the C# Community

MSDN Blog

Dustin Campbell