Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Creating a code file with common definitions/constants/enums etc?

Tags:

c#

In C++ I'd often create a code file containing constants, enums, #define-s, macros etc.

What's the best practice for that in C#? Do I create a static class and fill it with that data? or is there some other way ?

like image 900
Maciek Avatar asked Dec 06 '22 04:12

Maciek


2 Answers

You don't need a static class for enums - they can be top-level (meaning: namespace level). Yes, you need a class for constants (and a static class would suffice), but I would tend to have multiple classes - one per intent. There is no need to cram them all together.

In C#, any #define only apply to that file, so there is not much point having a class for them (put them in the project / build-script instead). And macros don't exist.

like image 84
Marc Gravell Avatar answered May 10 '23 23:05

Marc Gravell


If you have some items you want to define Globally, like a set of strings, I would use a static class with Static properties. I would do that if you are going to use it in more than 1 place.

If you are going to use a defined string for example in just once place, then I would put it in the class that is referencing it.

It is very important to use properties and not expose members. I have found with C++ developers I have worked with when they move to C# they expose members because they have no need for "the special logic of a property". While that may be true when you initially are writing the code. If you expose it as a member and need to do special logic then you have to refactor in a major way. While if you begin as a property then you can add the logic with no refactoring.

For Enums I tpyically define an Enum.cs file inside the folder that represents the namespace. Rather than define them inside a static class.

like image 20
David Basarab Avatar answered May 11 '23 01:05

David Basarab