UpTide UpTide - 6 months ago 36
C# Question

C# Premade Array?

Edit to explain how this is not a duplicate question: (feels like maybe this should be in meta)

1 - my question shows ignorance as to what the proper terminology is for the object in question.

2 - my question is NOT about the usefulness at all about the object in question.

These two points are understood by the first line of my question "Apologies in advance, I do not know the terminology so bear with me here." and a clear lack of questioning of what I could do with the object respectfully.




Apologies in advance, I do not know the terminology so bear with me here.

I want to build an object/list that is just like the
System.ConsoleColor
object.

What I mean is that for
ConsoleColor
there are a set number of attributes in an array and you can choose something friendly like 'blue' instead of having to remember that 9 is blue.

So for my function I want to be able to do something like the below, where
foo
is a
MyObject
that can only be
Type1
or
Type2
.

public void MyFunction(MyObject foo) {
switch (foo) {
case MyObject.Type1:
Console.WriteLine("myobject's type1");
break;
case MyObject.Type2:
Console.WriteLine("myobject's type2");
break;
}
}


Thank you.

Answer Source

You want an enumeration:

public enum MyObject
{
    Type1,
    Type2
}

public class Program
{
    public static void Main(string[] args)
    {
        MyObject foo = MyObject.Type1;
        switch (foo) {
            case MyObject.Type1:
                Console.WriteLine("myobject's type1");
            break;
            case MyObject.Type2:
                Console.WriteLine("myobject's type2");
                break;
        }
    }
}