New Book: C# Succinctly

My latest book, C# Succinctly, is now available. This is published by Syncfusion, as part of their Succinctly series. It’s an e-book and is free for you to download in multiple formats.


The Succinctly series is designed for a quick look at a specific topic. In that spirit, C# Succinctly does a quick overview of the C# programming language, covering the essentials of what a developer needs to get started. The code for this book is based on C# v6.0 and runs in Visual Studio 2015, which will be available within a couple weeks of this posting. The code is hosted on Bitbucket and you can find the link inside the book too.

Thanks to the folks at Syncfusion who helped me write this: Hillary Bowling, Stephen Haunts, Ben Ball, and Graham High.



What’s New in C# 6.0: Auto-Property Initializers

Today, Somasegar announced that Visual Studio 2015 will be released on July 20th, 2015. This release will also include C# 6.0. This is the first in a series of posts on the new features of C# 6.0 and I’ll cover Auto-Property Initializers. This post discusses what an Auto-Property Initializer is, how to use it, and why it can help you write code more efficiently.

What is an Auto-Property Initializer?

An auto-property initializer allows you to set the value of a property at the same time you declare it in a class. Prior to C# 6.0, you need to set the property value in a constructor. This is normally not a problem because in the simple case, you set the value in a constructor, like this, and move on:

    public class PepperoniPizza
        public decimal ExtraPrice { get; set; }

        public PepperoniPizza()
            ExtraPrice = 0.25m;

This PepperoniPizza class has an ExtraPrice property, which is initialized in the constructor. That’s fine, but a couple considerations might be that 1) you need to explicitly declare a constructor just to initialize the value, 2) alternatively, you could have created a fully-implemented property and initialized the backing store field, 3) what if you have multiple properties, and/or 4) what if you have multiple constructors causing you to duplicate the initialization. In each case, you’re doing more work as well as separating initialization from declaration. Auto-property initializers let you do the opposite and combine declaration with initialization, like this:

    public class PepperoniPizza
        public decimal ExtraPrice { get; set; } = 0.25m;

With auto-property initializers, declare the auto-property as normal, but also use an assignment operator, specifying the value to initialize the property with. Then end the statement with a semi-colon. While you might not see this as a huge addition to the language, combined with several other features, this supports the C# 6.0 theme of having a set of features that simplify and make coding faster.

Accessors With Different Visibility

You can initialize auto-properties that have different visibility on accessors. Here’s an example with a protected setter:

        public string Name { get; protected set; } = "Cheeze";

The accessor can also be internal, internal protected, or private. The getter can also have different visibility and you will still be able to initialize the auto-property.

Read-Only Properties

In addition to flexibility with visibility, you can also initialize read-only auto-properties. Here’s an example:

        public List<string> Ingredients { get; } = 
            new List<string> { "dough", "sauce", "cheese" };

This example also shows how to initialize a property with a complex type. Also, auto-properties can’t be write-only, so that also precludes write-only initialization.

Initialization Expressions

Although the previous example initialized with a new List<string> instance, the value is still a static reference. Here are a couple more examples of expressions you can initialize auto-properties with:

        public decimal Price2 { get; set; } = 1m + 2m;

        public double Price3 { get; set; } = Math.PI;

The Price2 initializer is an addition expression, but the values are still numeric literals. Along the same lines, Math.PI is a constant initializer for Price3.

Non-Static Initializers are Verboten!

All of the initializers you’ve seen so far evaluate to a static expression. Non-static expressions, like the ones below, will generate compiler errors:

        // compiler errors
        //public string Name2 { get; set; } = Name;
        //public decimal Price4 { get; set; } = InitMe();

        decimal InitMe() { return 5m; }

The code tries to initialize Name2 with the value of Name, another property, which won’t work. Similarly, InitMe() is an instance method that won’t compile when used as the initializer for Price4. It doesn’t matter that InitMe() returns a numeric literal. Both of these situations generate a compiler error. Here's the error message for Price4:

    A field initializer cannot reference the non-static field, method, or property 'PizzaBase.InitMe()'

Virtual Properties and Type Initialization

A virtual auto-property can be initialized too. Here’s an example:

        public virtual decimal Price { get; set; } = 3.00m;

During initialization of the containing type, Price initializes before the constructor executes. It initializes like a field, meaning that a Price property override isn’t called during auto-property initialization. If you wanted the polymorphic initialization, you should initialize Price in the base class constructor, like this:

    public abstract class PizzaBase
        public string Name { get; protected set; } = "Cheeze";

        public virtual decimal Price { get; set; } = 3.00m;

        public PizzaBase(IEnumerable extraIngredients)
            Price = 2.95m;

The abstract PizzaBase class is a base class for the PepperoniPizza class shown below. This class overrides the Price property:

    public class PepperoniPizza : PizzaBase
        public decimal ExtraPrice { get; set; } = 0.25m;

        decimal price;
        public override decimal Price
                return price;

                price = value + .50m;

        public PepperoniPizza(decimal extraFees) : base(new List { "pepperoni" })
            ExtraPrice += extraFees;
            Name = "Pepperoni";

This is a scenario that’s more elegant to demo live, but you can test this by adding a full Price property override in a derived class (as shown in PepperoniPizza above), setting the setter breakpoint, and stepping through the code with the base class auto-property initializer. The base class Price auto-property initializer executes, but doesn’t call the full Price property setter in the derived class. Next, add a statement to the base class constructor to set Price to any value (as shown in PizzaBase above), step through the code, and observe that the assignment in the base class constructor does call the derived class full Price property when executed.


You’ve now been introduced to auto-property initializers. At the simplest level, but assign a value to an auto property where it’s declared. You learned that you can initialize read-only properties and the values must evaluate to a static expression. Non-static initializers cause compiler errors. This post also explained how auto-properties initialize like fields, but you can get polymorphism by initializing the auto-property in a constructor instead. Auto-property initializers, as one of a set of new features, are a new tool to help you write simpler code and save a few extra keystrokes.


Free Webinar: What’s New in C# 6.0

I'll be doing a Free Webinar on 6/24/2015 with on What's New in C# 6.0:

Here’s the abstract:

C# 6.0 offers several new features that help streamline your code. You'll learn about string interpolation, property initializers, exception filters, and more. You'll also learn about some of the new features of Visual Studio 2015. This presentation will help you understand how these features work and why they can help you be more productive. Bring your questions -- there will be plenty of Q&A time at the end of the session.


Hosting LINQ to Twitter on GitHub

Today, I finished migrating LINQ to Twitter from CodePlex to GitHub. I was happy with CodePlex for a long time. However, it just hasn’t been kept up to date. There hasn’t been any activity or improvements to the site in over two years. After watching the deterioration for a while, I decided to follow the lead of the the C# Team and other Microsoft projects and move to GitHub. Here’s the URL:


    LINQ to Twitter on GitHub


Just to be clear, I thought was a very nice site and would have liked to host my code there forever. I appreciate all the work the developers put into it and how it supported the community.



What’s New in VS 2015 Webinar

Today, I did a webinar for, titled “What’s New in Visual Studio 2015”. I provided an overview of IDE features, editor enhancements, ASP.NET updates, the new Universal App project type, Mobile application development, and debugging. This is free, so you can view it on-line here:

You can also access code and slides on my Github account:


Visual Studio 2015 Custom Window Layouts

I’ve been trying out VS 2015’s new Custom Window Layouts feature. This lets you create, manage, and open different arrangements of windows in Visual Studio. The benefit of custom layouts is that you can quickly switch between window layouts that help you perform specific tasks, saving you time from going through the layout process to support scenarios you commonly engage in. Clearly, the selection of these scenarios, and associated layouts, is a personal choice and based on how you prefer to work. This blog post explains how to use the Custom Window Layouts features.

Finding Available Layout Options

You can work with custom window layouts via the top-level Window menu in VS 2015, shown below:


This shows that you can save, apply, manage, and reset the window layout. The following sections go into more depth on each feature.

Saving a Layout

The scenario I’ll use for this demo layout is reference management. Whenever I’m managing project references, it’s handy to have the NuGet window, NuGet Console, and Solution Explorer in view. Additionally, having the Properties window open lets me quickly select project references and view their details. The following screen shot shows what this looks like:


To save this layout, select the Window | Save Window Layout menu option. You’ll see the following dialog window:


Add the Layout name and click OK and you’ll have a new layout that you can apply.

Note: You can save up to 10 layouts.

Applying Layouts

Once you have saved layouts, you can switch between them. i.e. apply a new layout. To apply a new layout, select the Window | Apply Window Layout menu option and then select the layout you want, as shown below.


Selecting References Layout will move your screen windows into the arrangement specified when saving the References Layout. Notice that each layout also has Ctrl+Alt+N short-cut keys, where N is a number from 0 to 9.

Managing Layouts

Once you have a set of layouts, you’ll likely want to change what you have. For this, select the Window | Manage Window Layouts menu option and you’ll see the Manage Window Layouts dialog window below:


This window lets you re-order layouts by selecting the layout to move and clicking the up or down arrow buttons. Be aware that the short-cut keys are based on position in the list and not assigned to a specific layout. So, if you move Full Screen (in the figure above) up, it’s short-cut changes from Ctrl+Alt+2 to Ctrl+Alt+1. The Rename and Delete buttons do what they say to the selected layout.

Resetting the Layout

If you select the Window | Reset Window Layout menu option, the window layout will revert to the original layout that Visual Studio established when installing. If you recall, Visual Studio asks you for a profile, such as C# or ASP.NET, and that determined what the original layout was. While you can reset the layout, all of your custom layouts remain intact and you can continue to use them normally.


Custom Window Layouts give you a quick way to customize your IDE layout, depending on the work you want to do. You can save, apply, and manage layouts to match your preferences.

If you would like to learn more about Visual Studio 2015, I’ll be presenting a free webinar on “What’s New in Visual Studio 2015” on Wednesday, April 22nd 2015 for


Uploading Multiple Images in Parallel with Async and LINQ to Twitter

The Twitter API recently deprecated the statuses/update_with_media endpoint, which LINQ to Twitter abstracts via a TweetWithMedia method. It’s replaced with a new endpoint, media/upload, and a new parameter to statuses/update, media_ids. The benefit of the new API change is that you can now tweet multiple images. Naturally, LINQ to Twitter supports this capability. However, what’s really interesting is that you can upload multiple images at the same time with Task.WhenAll. This post explains how to do this.

Uploading Images

The first step to tweeting multiple images is to upload the images you need. You can do this with LINQ to Twitter’s new UploadMediaAsync method, like this:

    Media uploadedMedia = await twitterCtx.UploadMediaAsync(File.ReadAllBytes(@"..\..\images\200xColor_2.png"))

The UploadMediaAsync method takes a byte[] and returns a Media instance. The Media instance is important because it contains a MediaID that Twitter assigned to identify the uploaded image. You’ll see how to use this in a later section of this post. As with all other LINQ to Twitter commands and queries, UploadMediaAsync runs asynchronously.

Uploading Multiple Images in Parallel

You can upload multiple images in parallel via the Task.WhenAll method, which accepts a collection of Task<TResult>. Here’s how to upload multiple images in parallel to Twitter:

            var imageUploadTasks = 
                new List<Task<Media>> 

            await Task.WhenAll(imageUploadTasks);

This example creates a List of Task<Media> and awaits Task.WhenAll. This causes the program to pause, waiting for the three invocations of UploadMediaAsync to complete. When each method completes, Task.WhenAll returns. You then need to associate these images with a tweet.

Tweeting Multiple Images

Once each method completes and Task.WhenAll returns, you can tweet the images. The following code gets a list of MediaID that Twitter returns and performs a tweet that includes the uploaded images:

            var mediaIds =
                (from tsk in imageUploadTasks
                 select tsk.Result.MediaID)

            Status tweet = await twitterCtx.TweetAsync(status, mediaIds);

The UploadMediaAsync method returns a Media instance that contains a MediaID that Twitter uses to identify each uploaded image. In the code above, you can see how to pull those values from the collection that was originally passed to Task.WhenAll, imageUploadTasks. Then use the new overload of TweetAsync to pass that list, mediaIds, as a parameter (with tweet text in the status parameter).

This results in a tweet that contains text and will display the three images uploaded.

For more info on Twitter API constraints and details of the multi-image process, visit the Twitter API documentation, Uploading Media: Multiple Photos.



Released LINQ to Twitter v3.0.5

The new version of LINQ to Twitter v3.0.5 adds support for uploading multiple images in a tweet. There’s also several bug fixes, including fixing a serious bug that affected VB developers. You can download the latest on CodePlex or via NuGet.



Binding failure error – Cannot start the website because administrative privileges are required to bind to the hostname or port

The subject error just pops up for a project that has been running fine for a long time. It comes from IIS Express when running a Web application in Visual Studio. I’m not sure what causes it, but it might have been a side-effect of debugging other errors with Hyper-V and VPN. Looking around, the advice for fixing this was sparse and/or the typical VS repair/rebuild recommendation. Figuring out how to run as Administrator isn’t a valid solution either because it’s less secure and these days I can do a lot of work in VS without being administrator, like I was doing in this project. I did find one blog post, by Mark Hugh Neri, that was a good solution:

Workaround for URL binding failure error in IISExpress

The only thing I did different is that in VS you can right click the project, select Unload Project, and then right click again and select Edit ProjectName.csproj. After that, you can right click the project and select Reload Project to start working again. Removing the DevelopmentServerPort and IISUrl tags causes VS to re-generate a port number and the project works well after that. Another thing I did was to open my Documents\IISExpress\Config\applicationHost.config file and delete the old sites, but I’m not sure it was necessary.


Updated UserStreamsParser for LinqToTwitter

azyobuzin has updated his UserStreamsParser for LinqToTwitter: