C# 6 solves magic strings problem

If you haven’t already, download Visual Studio 2015 RC and check out C# 6.0! First thing I am enthousiastic about is the brand new nameof keyword.

Create a new  Console Application, name it NewPossibilitiesC6 and add a class named Person. Copy the following code in Person.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewPossibilitiesC6
{
class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public string Name { get; set; }

private int _age;

public int Age
{
get
{
return _age;
}
set
{
_age = value;
OnNotifyPropertyChanged(nameof(Age));

}
}

private void OnNotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));

}

}

public char Gender { get; set; }

public Person(string name, int age, char gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}

public void IncrementAge()
{
this.Age++;
}
}
}

Copy the following code in the automatically generated Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewPossibilitiesC6
{
class Program
{
static void Main(string[] args)
{

int age = 35;
Person person = new Person(“John”, age, ‘m’);

person.PropertyChanged += person_PropertyChanged;

Console.WriteLine(String.Format(“Value of property Name: {0}”, person.Name));

Console.WriteLine(String.Format(“Identifier of property Name: {0}”, nameof(person.Name)));

person.IncrementAge();

int newAge = person.Age;

Console.WriteLine(String.Format(“Method {0} was called and changed {1} from {2} to {3}”, nameof(person.IncrementAge), nameof(person.Age), age, newAge));

try
{
newAge = newAge / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine(String.Format(“The exception is {0}, with message {1} and the involved variable is {2}”, nameof(DivideByZeroException), ex.Message, nameof(newAge)));
}

Console.ReadKey(true);
}

private static void person_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(Person.Age):
Console.WriteLine(String.Format(“The property {0} changed”, nameof(Person.Age)));
break;
default:
break;
}
}
}
}

When you run this program you should see the following screen:

2015-05-15 13_47_53-Greenshot

What do we see here?
Line #1: First we simply see the value stored in the Name property of Person, which in this case is “John”.
Line #2: But then we see the all new nameof keyword at work writing to the console not the value, but the actual name of the property, which in this case is Name!
Line #3: The method IncrementAge is called which mutates the value of property Age. This causes the event PropertyChanged to be thrown. This event is handled at the method person_PropertyChanged. To determine which property fired the event we use the nameof keyword again and nót a string literal and we write the appropiate message to the Console.*
Line #4: Demonstration of the fact that you can use the nameof keyword on anything! Here we display the actual name of the method being called, which could be handy with exception handling. To demonstrate this…
Line #5: It can also be used on class names to for instance show the name of the exception class in a safe manner. But that is not even the best way to use it, see how the name of the local variable newAge which was involved with the exception is displayed on the console.

So why is this so cool?! We agree we all want to get rid of magic numbers and strings right? Well I don’t know about you guys, but by writing WPF applications my ViewModels got bogged down with magic strings. See property Age in class Person. We used to write the OnNotifyPropertyChanged like so (make these changes in your code also please):

OnNotifyPropertyChanged(“Age”);

And in the eventhandler like this (again make the change please):

switch (e.PropertyName)
{
case “Age”:
Console.WriteLine(String.Format(“The property Age changed”));
break;
default:
break;
}

Now change the name of property Age to EstimatedAge press CTRL + . and have it rename across your application. Noticed how the string literals don’t change along? Visual Studio has no way of telling that the “Age” string literal refers to the property Age. Change “Age” on both places to nameof(EstimatedAge) please. Next change the property EstimatedAge back to Age please and hit Ctrl + . to rename is throughout your application. Notice how everywhere in your code the change has been done properly. And that is why from now on I encourage everyone to use the nameof keyword when possible.

The chance on bugs has been reduced significantly once again by the great developers at Microsoft. And thank you for reading my post. Leave a comment if you liked it or have anything to say about the nameof keyword.

*I know the switch case has no practical use, it is just used to make an example.

Advertisements

About Danny

Bachelor in Commercial ICT MCTS Winforms .NET 2.0 MCTS ASP.NET 3.5 PSM I
This entry was posted in .NET programming, C#, C# 6.0 and tagged , , . Bookmark the permalink.

4 Responses to C# 6 solves magic strings problem

  1. So they kluged a fix for a poorly implemented idea (really? strings? no object? This is almost as bad as when we went from Databases to XML)

    • Danny says:

      Perhaps it is the monday morning effect and I haven’t had my coffee yet. But what poorly implemented idea are you refering to exactly? And what do you mean with going from databases to XML?

  2. Pingback: C# 6 solves verbose null checks | Danny van der Kraan's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s