C# Public Enums in Classes

C#Enums

C# Problem Overview


I have a program with a class that contains a public enum, as follows:

public class Card
{
    public enum card_suits
    {
        Clubs,
        Hearts,
        Spades,
        Diamonds
    }
...

I want to use this elsewhere in my project, but can't do that without using Card.card_suit. Does anyone know if there's a way in C# to declare this so that I am able to declare

card_suits suit;

Without referencing the class that it's in?

C# Solutions


Solution 1 - C#

Currently, your enum is nested inside of your Card class. All you have to do is move the definition of the enum out of the class:

// A better name which follows conventions instead of card_suits is
public enum CardSuit
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
}

To Specify:

The name change from card_suits to CardSuit was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).

Solution 2 - C#

You need to define the enum outside of the class.

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
     // ...

That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.

Solution 3 - C#

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

Solution 4 - C#

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul MichaelsView Question on Stackoverflow
Solution 1 - C#Justin NiessnerView Answer on Stackoverflow
Solution 2 - C#Reed CopseyView Answer on Stackoverflow
Solution 3 - C#Paul SasikView Answer on Stackoverflow
Solution 4 - C#Paulo AlexandreView Answer on Stackoverflow