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()
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With