Magic String Dilemma And C# 6.0

Ever heard about Magic String? What are they? Where are they used? Why do we need them? Do we already know them?

The answer to all these questions is: Yes. We know them and we use them on daily basis and our life cannot work without them.

What are they?

They are expression like hard coded string values which we believe would never change. Or even if they change, we take care of them by declaring constants at the beginning of our program. This way, we write once and use it everywhere. One more solution to this is to create string constants in .resx resource file in C# domain.

What’s wrong with them?

Magic strings are error-prone. Often they are widely used throughout your application, in case in future you need to change them; you have to change them one by one. The dark side of this is that you may miss a few places. Your program wont crash, but it may happen that it does not the right or meaningful message to the user.

Example:

If you ever used WPF, it’s more likely that you came across with firing PropertyChanged event on public properties. I am pretty sure that most of us write code like this. Don’t we?

  1. /// <summary>  
  2. /// Public Property for name  
  3. /// </summary>  
  4. public string Name  
  5. {  
  6.     get { return _person.Name; }  
  7.     set  
  8.     {  
  9.         if (value != Name)  
  10.         {  
  11.             _person.Name = value;  
  12.             //Magic String "Name"  
  13.             OnpropertyChanged("Name");  
  14.         }  
  15.     }  
  16. }  
If answer to my question is YES, we all have nightmares when one of the properties’ name is changed and we forgot to change it in “OnpropertyChanged("Name")”. We wondered why over UI did not respond as expected. Assuming, most of the refactoring techniques do not also cover this case, we spent/wasted a lot of time in debugging our application and finally landed at a place where the actual problem was.

Remedy to the Problem:

Developer waited for a long time and some of them implemented their own solution to tackle the problem. But I am sure it was difficult at developer front. With C# 6.0, handling magic string has become really easy. C# 6.0 has introduced a new operator called nameof. nameof returns name of the element passed to it whether it’s a class name, method name, parameter name or particular attribute name. Applying NameOf operator in our problem would be so much easier:
  1. /// <summary>  
  2. /// Public Property for name  
  3. /// </summary>  
  4. public string Name  
  5. {  
  6.     get { return _person.Name; }  
  7.     set  
  8.     {  
  9.         if (value != Name)  
  10.         {  
  11.             _person.Name = value;  
  12.             //Magic String "Name" Replaced with NameOf  
  13.             OnpropertyChanged(nameOf(Name));  
  14.         }  
  15.     }  
  16. }  
So from now, start using nameof operator and get rid of magic strings.

 


Similar Articles