Cragly
Cragly

Reputation: 3626

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, where 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.

Upvotes: 0

Views: 1016

Answers (4)

CesarGon
CesarGon

Reputation: 15335

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.

Upvotes: 8

jason
jason

Reputation: 241711

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

Upvotes: 1

Shantanu Gupta
Shantanu Gupta

Reputation: 21108

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

Upvotes: 2

ram
ram

Reputation: 11626

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

Upvotes: 1

Related Questions