Coder Perfect

Is it necessary for C# enums to have their own file? [closed]


I have a class that uses an enumeration; however, the enumeration is now in its own file, which seems inefficient.

What is the consensus on enums being placed in the namespace of a file in which they are consumed? Is it necessary for the enum to have its own cs file?


I should point you that external callers, as well as the class in question, use these enumerations. In other words, these enumerations can be set by another class. So they aren’t used within the class; otherwise, this would be a no-brainer question.

Asked by Finglas

Solution #1

Although I wouldn’t call it “wasteful” (how much does an extra file cost? ), it is frequently inconvenient. I usually place the classes that are most directly associated with the enum in the same file.

Answered by James Curran

Solution #2

This is purely a personal choice.

Each enumeration should be kept in its own file, in my opinion (likewise for each interface, class, and struct, no matter how small). When I’m coming from another solution or don’t have a reference to the type in question, it makes them easy to find.

It’s also easier to discover changes in source control systems without diffing if each file has a single type.

Answered by 2 revs

Solution #3

This is completely a matter of personal preference. In my solution, I usually have a file called Enums.cs that collects all of the enum declarations.

However, they are usually found by pressing the F12 key.

Answered by Fredrik Mörk

Solution #4

Is there anything about an enumeration type in C# that suggests I should handle it differently from any other types I create?

If the enumeration is open to the public, it should be regarded similarly to any other open type. Declare it as a nested member of the class that uses it if it is private. Simply because one is an enumeration, there is no compelling reason to add two public types in the same file. All that matters is that it is a public type; the type’s flavor is unimportant.

Answered by Bryan Watts

Solution #5

Source control is another benefit of putting each type (class, struct, enum) in its own file. You can easily obtain the type’s whole history.

Answered by Tommy Carlier

Post is based on