All posts by Gigi

C# 6 Preview: using static

Update 31st January 2015: The syntax for using static has changed as from VS2015 CTP5. Please see C# 6 Preview: Changes in VS2015 CTP 5 for the latest syntax and examples. This article remains available due to historical significance.

Take a look at this little VB .NET program:

Module Module1

    Sub Main()

        Console.WriteLine("Hello world!")
        Console.ReadLine()

    End Sub

End Module

In VB .NET, you can take the Console static class name out of there and put it in the imports:

Imports System.Console

Module Module1

    Sub Main()

        WriteLine("Hello world!")
        ReadLine()

    End Sub

End Module

In fact, that feature works for any static class. And now, this feature is being added to C# starting from version 6. Let’s see the same example in C#. This is as you would write it in C# 5:

using System;

namespace UsingStaticHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");
            Console.ReadLine();
        }
    }
}

And this is how it looks like with the new static using feature in C# 6:

using System.Console;

namespace UsingStaticHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello world!");
            ReadLine();
        }
    }
}

Although most examples I’ve seen use this kind of scenario, I don’t think it’s a very good example of where this feature is useful. In fact, by extracting the static class name from the code that uses it, we’re reducing readability, and we’re also introducing the risk of ambiguity with other static classes that define the same method names. In this case we can’t add a static using for System.Diagnostics.Trace (which also has a WriteLine() method), but it’s quite easy to write a static Logger class that also defines a WriteLine() method, and that can be problematic.

However, the static using feature can be very useful in code that uses static methods heavily. A good example is mathematical calculations. Consider this code:

using System;

namespace UsingStaticMath
{
    class Program
    {
        static double CalculateSomething(double angle)
        {
            var numerator = Math.Sin(angle) * Math.Sin(angle) + Math.Cos(angle);
            var denominator = 1 + Math.Sqrt(Math.Sin(angle) + Math.Pow(Math.Cos(angle), 3));

            return Math.Pow(numerator / denominator, 2);
        }

        static void Main(string[] args)
        {
            var result = CalculateSomething(Math.PI / 2);

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

We can make it a whole lot more concise by introducing the using static:

using System;
using System.Math;

namespace UsingStaticMath
{
    class Program
    {
        static double CalculateSomething(double angle)
        {
            var numerator = Sin(angle) * Sin(angle) + Cos(angle);
            var denominator = 1 + Sqrt(Sin(angle) + Pow(Cos(angle), 3));

            return Pow(numerator / denominator, 2);
        }

        static void Main(string[] args)
        {
            var result = CalculateSomething(PI / 2);

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

In this case, when you read the code, it’s pretty obvious that Sin(), Cos(), Pow() and Sqrt() are mathematical functions, and it’s also very unlikely that there will be an ambiguity.

So in summary, the using static feature can be useful in some scenarios and disruptive in others. Use it wisely.

C# 6 Preview: nameof expressions

One of the new features in C# 6 is the new nameof operator. This will give you the name of a variable or type name, for instance nameof(id) gives you “id”. It’s a very simple feature. Let’s see a couple of examples where it is useful.

The simplest example is when checking whether arguments are null. I’ve got this simple Person class:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            if (firstName == null)
                throw new ArgumentNullException("firstName");
            if (lastName == null)
                throw new ArgumentNullException("lastName");

            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

Notice how I’m passing magic strings into the ArgumentNullExceptions. If I rename the arguments, then I must remember to update the magic strings as well.

Let us now take advantage of the new nameof() operator:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            if (firstName == null)
                throw new ArgumentNullException(nameof(firstName));
            if (lastName == null)
                throw new ArgumentNullException(nameof(lastName));

            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

It’s evident that with this change, if you rename the arguments, you will have to rename them throughout, or you will get a compiler error. No more magic strings.

Another scenario where this is really useful is when you are dealing with NotifyPropertyChanged in a WPF application. After implementing INotifyPropertyChanged in my ViewModel, I added the following property with a backing field to facilitate data binding:

        private string currentTime;

        public string CurrentTime
        {
            get
            {
                return this.currentTime;
            }
            set
            {
                this.currentTime = value;
                this.OnPropertyChanged("CurrentTime");
            }
        }

Here we have the same problem as before: we are using magic strings, and that can be problematic especially if we refactor our property and forget to update the property name in the string. Over the years, MVVM library developers have come up with various ways to mitigate this unpleasant scenario, including passing backing fields as ref parameters when raising the PropertyChanged event, using CallerMemberName, or using expression trees to pass in the property itself. nameof() again makes things a lot easier, as shown below. Even better, it is evaluated at compile-time, so there is no performance penalty associated with its use.

        private string currentTime;

        public string CurrentTime
        {
            get
            {
                return this.currentTime;
            }
            set
            {
                this.currentTime = value;
                this.OnPropertyChanged(nameof(CurrentTime));
            }
        }

On Detachment and Goodbyes

So as I explained in the welcome post, I am bidding goodbye to Programmer’s Ranch and starting something afresh with Gigi Labs. Programmer’s Ranch was probably my most successful website so far, and it is a little sad to let it go after slightly less than 18 months.

In life we come across many sad moments, and the demise of a blog is certainly among the least significant of these.  Whether we’re talking about a colleague leaving to pursue a new venture, or a friend who is emigrating, or someone close who just passed away, it is never easy to say goodbye.

There’s a nice conversation from Star Wars which I think contains a few nuggets of wisdom that apply in such cases. Taken from this question, here it goes:

Yoda: “Careful you must be when sensing the future, Anakin! The fear of loss is a path to the Dark Side.”

Anakin: “I won’t let my visions come true, Master Yoda.”

Yoda: “Rejoice for those around us who transform into the Force. Mourn them, do not. Miss them, do not. Attachment leads to jealousy, the shadow of greed, that is.”

Anakin: “What must I do, Master Yoda?”

Yoda: “Train yourself to let go of everything you fear to lose.”

This advice might sound a little bit brutal, but I think it depends very much on the interpretation. For me, detachment from the things and people that were an important part of our lives does not mean that we don’t care about them. It merely means that we accept that nothing lasts forever. It is for this reason that we make the most of the time we have available with them. And when the time comes to part ways, and for all the time thereafter, we remember and appreciate the part they played in our lives, and the part we played in theirs. Because each one of us has developed into who we are as a result of the interactions we had with others, much like invisible threads.

This also ties in with Buddhist teachings on attachment and liberation:

“The Buddha saw that people’s ignorance of the nature of change was the cause of suffering. We desire to hold on to what we value, and we suffer when life’s inevitable process of change separates us from those things. Liberation from suffering comes, he taught, when we are able to sever our attachments to the transient things of this world.

[…]

“The challenge is not to rid oneself of attachments but, in the words of Nichiren, to become enlightened concerning them. […]

“In their proper perspective–when we can see them clearly and master them rather than being mastered by them–desires and attachments enable us to lead interesting and significant lives.”

So perhaps Yoda will be disappointed to find out that we’ll still miss the people who are no longer a part of our lives. However I think he’d be pretty proud of us if, whenever a friend leaves for greener pastures (whether it means a new job, a new country, or whatever), we know in our heart that we played an important part in his/her personal development, and life in general.

Welcome to Gigi Labs

Hello everyone, and welcome to Gigi Labs!

This is not my first website, nor my first blog. I’ve actually been writing on the web for the past 12 years, starting with Dino’s Ultima Page and subsequently launching various different sites, some of which still exist today (such as Gigi’s Computer Corner). My most recent website was Programmer’s Ranch, a highly successful blog in which I would explain various programming topics in a concise and practical manner.

Programmer’s Ranch was based on the Blogger platform, which turned out to be a pretty poor choice for various reasons. It was very time-consuming to write decent-quality programming articles on a CMS that had no support whatsoever for syntax highlighting, among various other deficiencies. Less than 18 months after Programmer’s Ranch was launched on 2nd May 2013, I now find myself needing to create a new blog – Gigi Labs.

With Gigi Labs, I am taking things to a whole new level. Aside from continuing the legacy of Programmer’s Ranch with programming articles, I will also be writing about various other topics including PC games, music, workplace, etc.

This is a bit of a departure from my previous websites, which were each dedicated to a different aspect of my life and were completely hand-coded from the ground up (other than the blogs, naturally). For Gigi Labs I am using the power of the WordPress CMS to write about various topics and have them categorised neatly. Gigi Labs is where all those websites I created over the past 12 years converge.

Thanks for following Gigi Labs!