Reputation: 4513
I'm programming using C#, after programming on C. So I'm using a lot of constants such as "DEFAULT_USER_ID", "REMOTE_ADDRESS" and such...
It seems to me that it's pretty "old fashioned" to use such constants and maybe there is some other more elegant way for using some constant data between objects.
Any ideas on how this could be done elegantly?
Thanks.
Upvotes: 1
Views: 266
Reputation: 3731
You can always just use custom Enums so you get Visual Studio Intellisense.
Upvotes: 0
Reputation: 9436
How about config files? you guys don't use config files in C#? DEFAULT_USER_ID and REMOTE_ADDRESS look very much suited to be in a config file
Upvotes: 0
Reputation: 172270
Using constants for stuff like DEFAULT_USER_ID
is still "the way to go" (unless you want it to be configurable, but that's another topic). --> const (C# Reference)
Don't use constants for enumerations (FILE_TYPE_DOC = 1
, FILE_TYPE_XLS = 2
, ...). This can be done more elegantly in C# with enums:
enum FileType {
Doc,
Xls, // or, optionally, "Xls = 2".
...
};
You can also use this for flags (constants combinable by bitwise operators), which is another common use case of constants in C:
[Flags]
enum FontDecoration {
None = 0,
Bold = 1,
Italic = 2,
Underline = 4
}
Upvotes: 4
Reputation: 28279
Also you may define constants like that
public static class Defaults
{
public const string MyName = "SuperName";
}
public class MyClass
{
string s = Defaults.MyName;
}
In such case you may use class Defaults anywhere in your app
Also you may want to know that there is two ways of defining constant variables in Static readonly vs const
Upvotes: 1
Reputation: 37516
Another alternative is to store constant values in a .config file, that way you do not need to recompile your application to change your values if needed. Depending on how your code is being deployed, it may or may not be appropriate to have your settings exposed as plain text. See this article for a simple example of using a .config file: http://www.developer.com/net/net/article.php/3396111/Using-Application-Configuration-Files-in-NET.htm
Upvotes: 1
Reputation: 108800
static readonly
field instead of const
sometimes.enum
s instead of several integer constants.Upvotes: 2
Reputation: 1191
You can use static or readonly properties, for instance, for App class
class MyClass {
public static readonly int myVal=10;
}
Upvotes: 1