RobIII
RobIII

Reputation: 8821

C# equivalent for C code needed

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

static const value_string  message_id[] = {

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

Upvotes: 1

Views: 234

Answers (5)

tvanfosson
tvanfosson

Reputation: 532465

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

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

Upvotes: 5

Joel
Joel

Reputation: 19358

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.

Upvotes: 1

bdukes
bdukes

Reputation: 155935

    private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
        {
            { 0x0000, "Foo" }, 
            { 0x0001, "Bar" }
        };

Upvotes: 1

John Feminella
John Feminella

Reputation: 311536

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500715

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.

Upvotes: 1

Related Questions