Can anybody tell me the C# equivalent for this C code?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
Can anybody tell me the C# equivalent for this C code?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };
Then you can get the "string" version using Enum.Format()
or ToString()
.
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.
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.
private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
{
{ 0x0000, "Foo" },
{ 0x0001, "Bar" }
};
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.