The magic strings

The magic strings

The Magic Strings may look like something out of this space or something about which we can not discuss a lot because it is the Lord Voldemort of coding style.
Every blogger is excellent if you want to learn or read about something, but I am sorry to say that their focus is on the lines of blog post that you have to read in helping them increasing their visit time. If you find about Magic String in C# on the internet, then you will get trapped. Take it easy guys.Let’s go backwards about ADO.Net with C#.
When we were taking the data from the first column of the table in data reader, we were allowed to use string to match exactly against the column name or we had to get them through some index number.
Have you ever realized which approach is better?
For us, entering the string names of those columns in datareader was more comfortable than mentioning the index number of that column in the indexer field.
Say I am pointing out salary from the result given by the data reader like this :

Example 1: my_datareader[“Salary”];

or through index number

Example 2: my_datareader[0];

Which approach is better, you have to decide. In Example 1 , I used magic string “Salary” that was enclosed in quotation marks.

From an excerpt from, let’s see further:

Do not use literal values, either numeric or strings, in your code other than to define symbolic constants. Use the following pattern to define constants:
public class Whatever

/* try to avoid the hard coded string such as “Red” when object is created. new Color(0xFFEFD5) is an excellent example that is using the hash numbers for PapayaWhip color object */

public static readonly Color PapayaWhip = new Color(0xFFEFD5);
public const int MaxNumberOfWheels = 18;
There are exceptions: the values 0, 1 and null can nearly always be used safely. Very often the values 2 and -1 are OK as well. Strings intended for logging or tracing are exempt from this rule. Literals are allowed when their meaning is clear from the context, and not subject to future changes.
mean = (a + b) / 2; // okay
WaitMilliseconds(waitTimeInSeconds * 1000); // clear enough

Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.
Syed Adeel Ahmed on FacebookSyed Adeel Ahmed on GoogleSyed Adeel Ahmed on InstagramSyed Adeel Ahmed on Twitter