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?
- /// <summary>
- /// Public Property for name
- /// </summary>
- public string Name
- {
- get { return _person.Name; }
- set
- {
- if (value != Name)
- {
- _person.Name = value;
- //Magic String "Name"
- OnpropertyChanged("Name");
- }
- }
- }
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:
- /// <summary>
- /// Public Property for name
- /// </summary>
- public string Name
- {
- get { return _person.Name; }
- set
- {
- if (value != Name)
- {
- _person.Name = value;
- //Magic String "Name" Replaced with NameOf
- OnpropertyChanged(nameOf(Name));
- }
- }
- }

Saineshwar BageriPosted Sep 20, 2015, 1:08 AM
nice one
Santhakumar MunuswamyPosted Sep 17, 2015, 10:19 AM
Thanks for nice article:)
Harshad PansuriyaPosted Sep 17, 2015, 8:32 AM
Nice one
Sibeesh VenuPosted Sep 17, 2015, 6:25 AM
Nice Share
Sibeesh VenuPosted Sep 17, 2015, 6:24 AM
Nice Share
Ankit BansalPosted Sep 17, 2015, 4:33 AM
thanks for share..
Rajeesh MenothPosted Sep 17, 2015, 12:41 AM
Good One
Pankaj Kumar ChoudharyPosted Sep 16, 2015, 8:31 PM
Nice Explain Sir...........
Mohammed IbrahimPosted Sep 16, 2015, 2:29 PM
nice
Karthikeyan KPosted Sep 16, 2015, 12:22 PM
Good one sir...Thanks for sharing
Vipul MalhotraPosted Sep 16, 2015, 10:44 AM
Nice Article.Thanks for sharing
Vaikesh K PPosted Sep 16, 2015, 8:56 AM
Nice Share
RakeshPosted Sep 16, 2015, 8:11 AM
Nice share
Harshad PansuriyaPosted Sep 16, 2015, 7:39 AM
Nice one