tags:

views:

263

answers:

3

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?

+24  A: 

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).

Justin Niessner
But I only want to declare it in one place, yet use it throughout the namespace
pm_2
You'll still have access to it throughout the namespace with declaring it only one time.
Justin Niessner
@pm_2 following Justin's answer would allow you to do exactly that.
Rowland Shaw
Others have mentioned that CardSuit is preferred to CardSuits without explaining why. The Plural Form implies that it will be an enumeration of flags that can be ORed together.
Martin Smith
+1 for naming conventions. :)
fre0n
@Justin: Nice answer, I didn't knew that we could declare enum outside class also
Shantanu Gupta
+9  A: 

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.

Reed Copsey
+5  A: 

Just do this: (Declare the enum outside the bounds of the class.)

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

public class Card
{

...

Remember that an enum is a type. You might also consider putting in its own file if it's going to be used frequently by many other classes. (From the looks of it i'm guessing that it will.)

Paul Sasik