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
        {
            get
            {
                return price;
            }

            set
            {
                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.

Summary

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.

@JoeMayo

Free Webinar: What’s New in C# 6.0

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

http://bit.ly/1POvqmJ

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.

@JoeMayo

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 CodePlex.com 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.

 

@JoeMayo

What’s New in VS 2015 Webinar

Today, I did a webinar for LearnNowOnline.com, 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:

http://bit.ly/1DiGNea

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

http://bit.ly/1EcBznV

@JoeMayo

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:

WindowLayoutOptions

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:

ReferenceManagementLayout

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

SaveLayout

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.

ApplyLayout

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:

ManageLayouts

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.

Summary

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 LearnNowOnline.com.

@JoeMayo

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>> 
                {
                    twitterCtx.UploadMediaAsync(File.ReadAllBytes(@"..\..\images\200xColor_2.png")),
                    twitterCtx.UploadMediaAsync(File.ReadAllBytes(@"..\..\images\WP_000003.jpg")),
                    twitterCtx.UploadMediaAsync(File.ReadAllBytes(@"..\..\images\13903749474_86bd1290de_o.jpg")),
                };

            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)
                .ToList();

            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.

 

@JoeMayo

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.

 

@JoeMayo

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.

@JoeMayo

Updated UserStreamsParser for LinqToTwitter

azyobuzin has updated his UserStreamsParser for LinqToTwitter:


https://userstreamex.codeplex.com/SourceControl/list/changesets


@JoeMayo

Dear XAML, We Meet Again

With Xamarin.Forms, Xamarin launched a new UI technology for cross-platform device development. Xamarin.Forms lets you use XAML to build your UI. I prefer to refer to the development target as a device, as opposed to mobile, because it seems that Xamarin is able to target anything that runs Android, iOS, or Windows – platforms that extend beyond phones and tablets to any type of electronic gadget (thing) running these OS’s regardless of whether they’re mobile, stationary, or any other executable endpoint on the Internet. That said, my focus today is on the visual, which Xamarin.Forms addresses well.

XAML first made it’s debut in Windows Presentation Foundation (WPF) as a more powerful desktop UI technology successor to Windows Forms. To less fanfare, XAML was the underlying representation for Windows Workflow Foundation (WWF) around the same time. In subsequent generations, XAML became an integral UI technology for Silverlight, Windows Phone, and Windows Store. XAML has more than proven it’s value as a capable UI technology and now we have a non-Microsoft implementation via Xamarin.Forms. In this blog post, I’ll walk through the initial set-up of a Xamarin.Forms app.

Choosing Tools

You can build Xamarin.Forms apps with either Xamarin Studio or Visual Studio. If you’re working with Visual Studio, you’ll need 2013 Update 2 because this is the release that supports shared projects. A shared project is a new project type that lets you share common code across multiple project types. I’m a huge Visual Studio fan, but am using Xamarin Studio in this post. To date, Xamarin Studio has worked well and the debugging experience for Xamarin technology development is better.

The type of app I’m building is Xamarin.Android v4.12.5. While Xamarin.Forms runs on iOS, Android, and Windows Phone, I decided to go with a very simple option for this post. Xamarin Studio supports Android well and you don’t need a separate machine to compile an Android app. As a side note, Xamarin.Android lets you target phones, tablets, Google Glass, and Google Wear. Pretty much, whatever platforms Apple and Google come out with, Xamarin will support within a matter of hours. All of this is very cool, but here I’ll just create a new phone app.

Creating the Project

To create the project, run Xamarin Studio. You should see something similar to this:

image

Next, create a new solution. You can click the New Solution button on the screen, select the menu File | New | Solution, or type Ctrl+Shift+N. This shows you the new solution window:

image

In the new solution window, select C#, Mobile Apps, and Blank App (Xamarin.Forms Shared). A shared project lets you share code between multiple project types. While this demo focuses on Android, there’s value in targeting multiple-platforms with Xamarin tools and the new shared project solution is a great way to provide that level of flexibility for future development. The other option for Portable Class Libraries (PCL) is well suited for creating a DLL that I can share with other developers on other projects and I would use a PCL project for that type of reuse. However, I want a shared project for sharing artifacts among potential technologies in this solution only. Name the project DearXaml, choose a location, and click OK and you’ll see the following project open in Xamarin Studio:

image

DearXaml is the shared project, with the App.cs file and DearXaml.Android is the main project that consumes the shared project. Notice how the DearXaml.Android project references the shared DearXaml project. On other platforms, or through Visual Studio, you would also have DearXaml.iOS and/or DearXaml.WindowsPhone projects. Now let’s see some startup code.

Examining Startup Code

At its heart, an Android app runs via Activities, which still remains true in the Xamarin.Forms world. Here’s the auto-generated activity from the New Solution wizard:

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

using Xamarin.Forms.Platform.Android;


namespace DearXaml.Android
{
	[Activity (Label = "DearXaml.Android.Android", MainLauncher = true)]
	public class MainActivity : AndroidActivity
	{
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			Xamarin.Forms.Forms.Init (this, bundle);

			SetPage (App.GetMainPage ());
		}
	}
}

As shown in the Activity attribute, the MainLauncher=true property setting means that this is the entry point of the application. The application calls OnCreate during the startup process, which executes Xamarin.Forms.Forms.Init(this, bundle) to initialize Xamaring.Forms. Then it calls SetPage with the App.GetMainPage argument. This is where we cross over into Xamarin.Forms territory. You can see that the following implementation of GetMainPage returns a Xamarin.Forms ContentPage:

using System;
using Xamarin.Forms;

namespace DearXaml
{
	public class App
	{
		public static Page GetMainPage ()
		{	
			return new ContentPage { 
				Content = new Label {
					Text = "Hello, Forms!",
					VerticalOptions = LayoutOptions.CenterAndExpand,
					HorizontalOptions = LayoutOptions.CenterAndExpand,
				},
			};
		}
	}
}

This ContentPage is a container page for the phone’s screen display. It sets its Content property to a centered Label – creating the classic “Hello” app experience. This default project sample demonstrates that you can write Xamarin.Forms apps with code. While coding is necessary for any degree of flexibility in UI development, there’s a lot of power to be had with declarative UI tools. So let’s rip this out and replace it with XAML.

Adding XAML Pages

What I’ll do is add a XAML page to the shared DearXaml project and then tell GetMainPage to return that new XAML page. To get started, right-click on the DearXaml share project and select Add | New File. You’ll see the New File windows below:

image

Select Forms and Forms ContentPage Xaml. The other option, Forms ContentView Xaml, lets you build a control (View) that fits on a screen, while the ContentPage (Page) is the whole screen. Set Name to HelloPage and click New to create a new XAML page in the DearXaml shared project. The location in the shared project is significant because now that Xamarin.Forms page can be shared among different project types, such as iOS, Android, and Windows Phone. Replace the contents of HellowPage.xaml with the following code:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage 
	xmlns="http://xamarin.com/schemas/2014/forms" 
	xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
	x:Class="DearXaml.HelloPage">
	<Label 
		HorizontalOptions="CenterAndExpand" 
		VerticalOptions="CenterAndExpand"
		Text="Hello Xamarin.Forms with XAML!"/>
</ContentPage>

Logically, this XAML is essentially the same as the class, represented by code, returned by the App.GetMainPage method. Notice the x:Class attribute on ContentPage – it corresponds to a partial class named HelloPage.cs that was created when this HelloPage.xaml was created. This XAML page is the other side of this partial page that you can instantiate. Now that the page is defined, replace the contents of the App.GetMainPage as follows:

using System;
using Xamarin.Forms;

namespace DearXaml
{
	public class App
	{
		public static Page GetMainPage ()
		{	
			return new HelloPage ();
		}
	}
}

Here, you only need to return an instance of the XAML page you want to display, HelloPage. That’s it, and now you can run the program.

Running the Program

Select the menu Build | Build All or press F8 to build the program and make sure it compiles. Then press F5 to run the program. You should see the Android emulator open and display the program something like this:

Note: The emulator is historically slow and takes even longer the first time you run it because it’s caching stuff.

image

One thing I really like about the current setup is that pressing F5 starts the emulator right away. Previous versions required manually loading the emulator and other magic tricks to get started. Kudos to the folks at Xamarin for automating this.

The Take-Away

Previous versions of Xamarin tools supported UI development, but those techniques were unique for each platform. With Xamarin.Forms, you can build the same screens to be shared across multiple technologies via PCLs and/or Shared Projects. This also sweetens the deal for enabling cross-platform device development with familiar tools of C#, and now XAML.