0

I have a library.

namespace Defintnions
{
    public class skywave
    {
        public enum partnum : byte { assembled, configured };
        public readonly string partnum_assembled = "1234B";
    }
}

I am testing it in this other project in the same solution.

using Defintnions;


namespace ConsoleApplication1
{
    class MainEntry
    {

        static void Main(string[] args)
        {
            string test3 = skywave.partnum.Assembled.ToString(); //assembled

            string zxcv = skywave.partnumAssembled; //doesnt compile
            skywave obj = new skywave();               
            string asdf = obj.partnumAssembled;       //1234B

            Console.WriteLine(test3);
            Console.WriteLine(asdf);
            Console.ReadKey(true);
        }
    }
}

I am confused why test3 doesn't require creation of the enum object locally.

I think its very clean though, which leads me to wonder if there is a way to do something similar, but instead have the output of the enum be an alphanumeric.

Ideally I would want my library to have the ability to do the following, but without the hassle of creating an object first.

string zxcv = skywave.partnum.assembled; //1234B
1
  • You're defining an enum type in your class, not a field whose type is an enum
    – juharr
    Jan 26, 2017 at 14:26

2 Answers 2

1

Enums are types in C#. In your code, skywave is a class that contains an enum called partwave. If you want to be able to reference partwave without reference to skywave, you need to define it outside of the class:

public enum partnum : byte { assembled, configured };
public class skywave
{
    public readonly string partnum_assembled = "1234B";
}

If you want to be able to refer to partnum_assembled without instantiating skywave, you need to define it as static or const

public class skywave
{
    public static readonly string partnum_assembled = "1234B";
}

or

public class skywave
{
    public const string partnum_assembled = "1234B";
}
1

A nested type (in this case an enum, although it would apply to any other variety of nested type) isn't accessed through an instance of the containing object, but rather through the containing object itself.

A particular instance of skywave doesn't contain the partnum type. The whole skywave class contains the type, so you access the enum through that type.

There is no implicit conversion from an enum to string, nor is there any way for you to create one. You would need to create your own custom type, emulating an Enum pattern, to have an implicit conversion to string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.