Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the better way to avoid magic string keys? Using string const keys in a class or using enumeration?

Tags:

c#

asp.net-mvc

My idea is to avoid magic string keys in my Asp.Net MVC application. To do so, I want to create string constant keys to be shared in the application.

For example, I can write TempData[MyClass.Message] or TempData[MyEnum.Message.ToString()] instead of TempData["Message"].

public class MyClass
{
    public const string Message = "Message";
}

and

public enum MyEnum
{
   Message,
   Others
}

My questions are: Which is the better way to avoid magic string keys? Using string const keys in a class or using enumeration together with ToString()?

like image 749
LaTeX Avatar asked Feb 14 '11 07:02

LaTeX


2 Answers

It is up to preference and usage.

You are able to accept the enumerated values in a strongly typed way:

public void SomeFunction(MyEnum someValue)
{
}

Or

TempData[MyEnum.Message]

With const strings, you can't.

You also have a built-in way to enumerate the values in an enum.

There is a third option which you haven't presented, and that is to place your "constants" in your configuration settings (App.Config). This will let you configure them after compile time. You might not need this now, but you might in the future, so it is worth considering.

One of these may be better for globalization purposes. I'm not sure which, since I've never globalized an app. Whichever works in satellite assemblies, I assume.

Basically, it comes down to what TempData is, and how you intend to use it.

like image 130
Merlyn Morgan-Graham Avatar answered Nov 03 '22 11:11

Merlyn Morgan-Graham


You should go for const strings as it can containt spaces/special chars as well, if those are your requirements. Otherwise change TempData to Dictionary<MyEnum,object> which is better approach.

like image 40
Mubashir Khan Avatar answered Nov 03 '22 10:11

Mubashir Khan