Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should you store your constant strings in .NET

Tags:

string

.net

Where should you store your commonly used strings for error messages, notifications, etc?

I used to put it into this global class that had a number of const strings but I've also seen some where it's stored in resource files. Where is the best place to put them in? I'm using .NET btw.

like image 364
Jonn Avatar asked Nov 29 '10 13:11

Jonn


People also ask

Where are constant strings stored in memory?

Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held. String str1 = "Hello"; directly, then JVM creates a String object with the given value in a String constant pool.

How do you keep a constant in C#?

In C# the #define preprocessor directive cannot be used to define constants in the way that is typically used in C and C++. To define constant values of integral types ( int , byte , and so on) use an enumerated type. For more information, see enum.

When to use constants C#?

The const keyword is typically used in C# language when there is an intention to have an immutable value across the system. Once a const field is initialized with a specific value, it can't be changed after that.


2 Answers

Resx is handy if you anticipate needing to swap them out - for example internationalization or per-instance customization. But it isn't hugely hard to move them manually between them. So: is it likely to need to change?

I would say: if you do keep them in code, try to keep the constants as tightly scoped as possible; if a constant only relates to User instances, for example, put it in User.

Likewise, things that won't change shouldn't be cluttering up a resx; for example, some internal well-known string that relates to the meaning of a value in a database... probably doesn't belong in resx even if you are using resx.

like image 114
Marc Gravell Avatar answered Oct 11 '22 01:10

Marc Gravell


I imagine if you ever want to translate/localize your product then resource files are going to be the best place to store those.

I am sure there are other advantages/disadvantages of both but that's the one that leaps into my head first.

like image 38
AndrewC Avatar answered Oct 10 '22 23:10

AndrewC