1

Can anybody tell me the C# equivalent for this C code?

static const value_string  message_id[] = {

  {0x0000, "Foo"},
  {0x0001, "Bar"},
  {0x0002, "Fubar"},
  ...
  ...
  ...
}

5 Answers 5

5
public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };

Then you can get the "string" version using Enum.Format() or ToString().

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

3 Comments

I actually like bdukes solution even better, but that is because I need the data in a dictionary anyway.
No problem. It just looked like something I would use an enum for -- absent any other context. You might also want to consider loading it from a config file rather than defining it in code. That way you wouldn't have to recompile your app to add another message id.
I know; but in my case I can safely hardcode it because I'm "dissecting" a protocol which doesn't change. If it does, I need to modify more than just the consts ;)
1
    private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
        {
            { 0x0000, "Foo" }, 
            { 0x0001, "Bar" }
        };

Comments

1

Something like:

MessageId[] messageIds = new MessageId[] {
    new MessageId(0x0000, "Foo"),
    new MessageId(0x0001, "Bar"),
    new MessageId(0x0002, "Fubar"),
    ...
};

(Where you define an appropriate MessageId constructor.)

That's the closest equivalent to the C code - but you should certainly consider whether an enum as per tvanfosson's answer might be a more appropriate design choice.

Comments

1
private const value_string message_id[] = {

  new value_string() { prop1 = 0x0000, prop2 = "Foo"},
  new value_string() { prop1 = 0x0001, prop2 = "Bar"},
  new value_string() { prop1 = 0x0002, prop2 = "Fubar"},
  ...
  ...
  ...
}

or better yet, if you are using it like a dictionary:

private const Dictionary<string, int> message_id = {

   {"Foo", 0},
   {"Bar", 1},
   {"Fubar", 2},
   ...
}

in which the string is your key to the value.

Comments

0

There won't be an exact match. C# does not allow static on const fields in classes. You can use readonly, though.

If you're using this in local scope, then you can get the benefit of anonymous typing and do this:

var identifierList = new[] {
    new MessageIdentifier(0x0000, "Foo"),
    new MessageIdentifier(0x0001, "Bar"),
    new MessageIdentifier(0x0002, "Fubar"),
    ...
};

I like this solution better, though.

Comments

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.