0

So I have this struct:

public struct PurchaseOrderStatus {
    public const string Open = "Open", Received = "Received";
}

How do I convert if I have the following:

    string status = "Open";

To:

    PurchaseOrderStatus.Open;

By Convert, I mean, how do I do this:

    PurchaseOrderStatus POS;
    String status = "Open";
    POS = status;
6
  • 1
    Define "convert", they both are the string "Open"... Commented Jul 23, 2012 at 16:12
  • I assume that you mean the equivilant of an enum.Parse("Open") for a struct? Not sure that there is one without using reflection...I would refactor your stuct to an enum if you can. Commented Jul 23, 2012 at 16:15
  • Yea, that is what I mean. I couldn't use enum because enum only store integer and I need to store string. Commented Jul 23, 2012 at 16:16
  • You say "i need to store string", just curious why? You can convert an enum to string as well. i.e. MyEnum.Open.ToString() will yield the string "Open" Commented Jul 23, 2012 at 16:19
  • Some enum have space in them. This would not work. Commented Jul 23, 2012 at 16:30

1 Answer 1

2

I would suggest using "smart enums" here:

public sealed class PurchaseOrderStatus
{
    public static readonly PurchaseOrderStatus Open =
        new PurchaseOrderStatus("Open");
    public static readonly PurchaseOrderStatus Received =
        new PurchaseOrderStatus("Received");

    private readonly string text;
    public string Text { get { return value; } }

    private PurchaseOrderStatus(string text)
    {
        this.text = text;
    }
}

You can store arbitrary information here, including text which wouldn't be valid identifiers (so long as it doesn't change, of course). It's still strongly typed (unlike your strings) and you can give other behaviour to it. You can even create subclasses if you remove the sealed modifier and add the subclasses as nested classes so they still have access to the private constructor.

Oh, and there's a genuinely limited set of values (the ones you've defined and null) unlike with regular enums.

The only downside is that you can't switch on it.

Sign up to request clarification or add additional context in comments.

1 Comment

If one is suitibly motivated you can also add onto this by adding 1) an intelligent Equals method 2) implicit conversion to string 3) explicit conversion from string 4) operator == overload 5) static enumeration of all possible values. Also consider whether you want it to be a class or a struct; either could be justified.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.