views:

150

answers:

5

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

static const value_string  message_id[] = {

  {0x0000, "Foo"},
  {0x0001, "Bar"},
  {0x0002, "Fubar"},
  ...
  ...
  ...
}
+5  A: 
public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };

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

tvanfosson
D'oh... was I thinking in the wrong direction. Do I feel stupid now...
RobIII
I actually like bdukes solution even better, but that is because I need the data in a dictionary anyway.
RobIII
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.
tvanfosson
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 ;)
RobIII
+1  A: 

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.

Jon Skeet
A: 

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.

John Feminella
+1  A: 
    private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
        {
            { 0x0000, "Foo" }, 
            { 0x0001, "Bar" }
        };
bdukes
This is even nicer!
RobIII
+1  A: 
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.

Joel Potter