I came from C/C++, and used alot things like #define OBJ_STATE_INPROCESS 2
, so that when coding actual logic you can have state = OBJ_STATE_INPROCESS;
, and what it does become more obvious than state = 2;
, which makes the code easier to maintain.
I wonder if there is some trick like this in C#
Asked
Active
Viewed 51 times
1

Qian2501
- 83
- 6
-
4Are you looking for: const int ObjStateInProgress = 2; ? – Peter Csala Sep 24 '22 at 08:41
2 Answers
3
Though technically a different concept, in C# you can use contants and enums to avoid "magic numbers", e.g.
public static class Constants
{
public const string MyConst = "ThisIsMyConst";
}
public enum MyEnum
{
MyEnumValue1,
MyEnumValue2,
}
// Usage
var value = MyEnum.MyEnumValue2;

Markus
- 20,838
- 4
- 31
- 55
-
Please mark your Constants class as static otherwise it could be instantiated. – Peter Csala Sep 24 '22 at 08:43
-
1@PeterCsala thanks for the hint - forgot about that when typing. I have changed the sample. – Markus Sep 24 '22 at 08:44
-
ok, although the `MyEnum.` or `Constants.` part would still looks a little messy, but I think I can live with it. – Qian2501 Sep 24 '22 at 08:48
-
1@Qian2501: In what way _messy_? `enum States{ InProgress = 2; }` Somewhere else: `state = States.InProgress;`. Is that messy? You can even give enums a [description](https://stackoverflow.com/questions/2650080/how-to-get-c-sharp-enum-description-from-value) message, in case you want to output more than `InProgress` or `2`. – Tim Schmelter Sep 24 '22 at 08:51
-
i dont get the need of an enum plus a static class with constants. are you looking for a way to define a constant and call it from anywhere ? – jmvcollaborator Sep 24 '22 at 08:53
-
`OBJ_STATE_INPROCESS` is cleaner than `StateEnum.OBJ_STATE_INPROCESS` when there is a lot of code, also you don't need `StateEnum.` part to understand what it does. But I think it's more of my C/C++ habit though, just a minor detail – Qian2501 Sep 24 '22 at 08:57
-
1@Qian2501, sure `StateEnum.OBJ_STATE_INPROCESS` is less clean. But honestly, who exactly is preventing you with all their might from creating/using something like `ObjState.Inprocess` or similar? I want to have a serious word with them... – Sep 24 '22 at 09:02
-
-
Haha, it's just getting a enum value dont need to specify the name of the enum in C/C++, or it's more often defined as a macro, so we always name it as such, but C# is different, just habit thing – Qian2501 Sep 24 '22 at 09:06
1
You can accomplish that using constant properties, for example:
static class Constants
{
public const int OBJ_STATE_INPROCESS = 2
}
class Program
{
static void Main()
{
Console.WriteLine(Constants.OBJ_STATE_INPROCESS ); //prints 2
}
}

jmvcollaborator
- 2,141
- 1
- 6
- 17
-
1
-
in C #define PROPERTY 2 is a constant, in terms of maintainability i believe this is what he is looking for.Just have a constant and call it from anywhere – jmvcollaborator Sep 24 '22 at 08:51