Rhubarb
Rhubarb

Reputation: 3993

What to do when an enum name clashes with a class name?

I have an enum Pitch and a class Pitch, both naturally to me should be named as such, however it's confusing to have both with the same name. Are there any guidelines for when an enum's name clashes with a class type?

EXAMPLE:

public enum Pitch
{
    Fastball,
    Sinker,
    Curveball
}

public class Pitch
{
}

Upvotes: 10

Views: 5757

Answers (6)

llessurt
llessurt

Reputation: 636

In the immediate instance where the enum is actually the identifier for the class, I settled on nesting the enum inside the class and naming it with the name: Option. I named the Option property: Id.

public class Pitch
{
    public Option Id { get; set; }

    public enum Option
    {
        Invalid = 0,
        Fastball = 1,
        Sinker = 2,
        Curveball = 3
    }
}

Upvotes: 0

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

Name the enum PitchType, PitchKind, PitchMagnitude, PitchQuality, PitchShape, PitchSpeed, PitchStrength or whatever fits best.


Another consideration is whether the class design could be improved. Instead of having a PitchType property inside the class Pitch, you could also create a class hierarchy:

public abstract class Pitch {}

public class Fastball : Pitch {}

public class Sinker : Pitch {}

public class Curveball : Pitch {}

Upvotes: 12

Greg Gum
Greg Gum

Reputation: 37875

public class Pitch
{
    public enum Enum {
        Fastball, 
        Curveball, 
        Sinker
    }
}

Pitch.Enum.Fastball

Upvotes: 0

Rajeev Kumar
Rajeev Kumar

Reputation: 51

When an enum is not embedded in a class make sure you use some different name before the label so as to prevent name clashes. You can also use namespaces as suggested by joey.

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

Embed the enum in the class:

public class Pitch
{
    public enum Kind {
        Fastball, 
        Curveball, 
        Sinker
    }
}

You can then access it through the class:

Pitch.Kind.Fastball

Upvotes: 4

Joey
Joey

Reputation: 354386

Use namespaces to group them logically. For the framework the class name is the full name, which may be MusicPlayer.Notes.Pitch and no just Pitch. Classes in different name spaces thus cannot clash.

Upvotes: 3

Related Questions