开发者

How to implement Global Strings C#

I have lots of global read only strings (around 100) that I am using in my application that will never change. I have been trying to think of the best solution that is easy to code and doesn’t have too much impact on performance. I need the strings to be used throughout the application like the example below, w开发者_StackOverflow中文版here Relationship is just a category in which the value is grouped and Alternate is the string value itself.

Relationship.Alternate

I have thought of creating static classes with static read only fields, static classes with const fields, implementing a Singleton pattern and even creating and parsing enums in a helper method. Can anybody provide some good advice on the best way to tackle this problem.


How about using resource files?

They are typed, easily accesible from your code at run-time, easily editable without need to recompile, and support any string content (i.e. not like enums, which only support identifier-like strings).

For example, you can add a resource file named GlobalStrings.resx to your C# project, and then add a string named Relationship_Alternate to that file. You can type any value you want for that string. In code, you would access the string value as:

GlobalStrings.Relationship_Alternate

Since those are identifiers validated at compile-time, you can guarantee that all your strings will load successfully at run-time.

Hope it helps.


Why dont u put them in enum which can make it memory efficient as well as readable along with less error prone


if they are going to be set at compile time you can try putting them in appSettings (in your web.config or app.config). This would typically apply for connection strings etc. If they are going to be set at run time, depending on some other value, you can go with static class & static read only fields

Edit:If you want them strongly typed, you can also use settings file . see MSDN article


You should consider using a resource file. See MSDN or solution B in this CodeProject article.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜