C# equivalent for C code needed - c#

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().

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

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.

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.

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.

Related

Dictionary with tuples values returning null?

I have a class with a dictionary defined as a private member :
Dictionary<int, (string, string)> arenaIdToSetAndNumber = new Dictionary<int, (string, string)>()
{
{ 70506, ("c16", "337") },
{ 70507, ("c16", "340") },
{ 70508, ("c16", "343") },
{ 70509, ("c16", "346") },
{ 70510, ("c16", "349") },
};
While debugging, I get to an item corresponding to key 70506, I see this with 2 watches:
I try doing var test = arenaIdToSetAndNumber[c.grpId].Item1 and test is set to null just as seen in the second watch! I don't understand why
The debugger and the watcher are not able to infer what is Item1 from the indexer operator [], thus will give you null in the watch. But once you run the code, it will just work fine for reading purpose. For writing purpose instead, you need to take out the whole tuple, edit it and reinsert in the dictionary:
static void Main(string[] args)
{
Dictionary<int, (string, string)> arenaIdToSetAndNumber = new Dictionary<int, (string, string)>()
{
{ 70506, ("c16", "337") },
{ 70507, ("c16", "340") },
{ 70508, ("c16", "343") },
{ 70509, ("c16", "346") },
{ 70510, ("c16", "349") },
};
var myTuple = arenaIdToSetAndNumber[70509];
myTuple.Item1 = "c18";
arenaIdToSetAndNumber[70509] = myTuple;
//System.Console.WriteLine(arenaIdToSetAndNumber[70509].Item1); // This prints c18
}
Otherwise, in one line, just recreate the whole tuple:
arenaIdToSetAndNumber[70509] = ("c18", arenaIdToSetAndNumber[70509].Item2);
All of this because the ValueTuple is a struct. Similar question here
This does not use tuples but solves your problem. Since you want to read the values create an immutable class, use properties to retrive the values.
public class Contents
{
private readonly string leftValue;
private readonly string rightValue;
public Contents(string aLeftValue, string aRightValue)
{
leftValue = aLeftValue;
rightValue = aRightValue;
}
public string LeftValue => leftValue;
public string RightValue => rightValue;
}
Modify your code to use the new class.
Dictionary<int, Contents> arenaIdToSetAndNumber = new Dictionary<int, Contents>()
{
{ 70506, new Contents("c16", "337") },
{ 70507, new Contents("c16", "340") },
{ 70508, new Contents("c16", "343") },
{ 70509, new Contents("c16", "346") },
{ 70510, new Contents("c16", "349") },
};
And you can test it with this.
var content = arenaIdToSetAndNumber[70506];
string leftValue = content.LeftValue;
string rightValue = content.RightValue;
Hope this solves your problem.

How to initialize List inherits from List C#?

I am new to inherit from list concept and I have a little confusion of initializing that.
Here is a simple example of my real code, here is my class that inherits from list:
public class List_Of_Int : List<int>
{
public string key{get; set;}
public List_Of_Int(string key)
{
this.key = key;
}
}
and here is where I need to initialize my variable:
List<int> list_of_int = new List<int>() { 1, 2, 3 };
List_Of_Int list_of_list = new List_Of_Int("some_key") **Some Code**
I want to assign list_of_int to my list_of_list, I believe there's a code replace some code that will do that, Is it true?
I know I can add by using AddRange(list_of_int ) later but I'm just wondering if I can do it while declaration?
Just wondering what you are asking actually but I guess this is what probably you are looking at
public class List_Of_Int
{
public List<int> key {get; set;}
public List_Of_Int(List<int> key)
{
this.key = key;
}
}
You can now initialize like
List<int> list_of_int = new List<int>() { 1, 2, 3 };
List_Of_Int list_of_list = new List_Of_Int(list_of_int)

How to add multiple values to list C#

Hi I have the following code when I am adding values to a list.
var NoLiftingList = new List<SQLFields>();
SQLFields nolifting = new SQLFields();
nolifting.Field1 = "No lifting";
NoLiftingList.Add(nolifting);
SQLFields extremelifting = new SQLFields();
extremelifting.Field1 = "Up to 100 lbs (extreme lifting)";
NoLiftingList.Add(extremelifting);
How can I simplify this? Instead of initializing a new object all the time.
This is the code for the whole class updated below.
Thanks
You can add to a list, and set properties on a class by using this inline constructor syntax (working example):
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var NoLiftingList = new List<SQLFields>
{
new SQLFields
{
Field1 = "No Lifting"
},
new SQLFields
{
Field1 = "Up to 100lbs (extreme lifting)"
}
};
}
}
public class SQLFields
{
public string Field1 { get; set; }
}
Use Object Initializers with anonymous types
var NoLiftingList = new List<SQLFields>(){
new SQLFields() { Field1 = "No lifting"},
new SQLFields() { Field1 = "Up to 100 lbs (extreme lifting)"}
};
Ref: MSDN Link
Try this
var NoLiftingList = new List<SQLFields>()
{
new SQLFields()
{
Field1 = "No lifting"
},
new SQLFields()
{
Field1 = "Up to 100 lbs (extreme lifting)"
}
};

Proper way to initialize a C# dictionary with values

I am creating a dictionary in a C# file with the following code:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT
= new Dictionary<string, XlFileFormat>
{
{"csv", XlFileFormat.xlCSV},
{"html", XlFileFormat.xlHtml}
};
There is a red line under new with the error:
Feature 'collection initilializer' cannot be used because it is not part of the ISO-2 C# language specification
What is going on here?
I am using .NET version 2.
I can't reproduce this issue in a simple .NET 4.0 console application:
static class Program
{
static void Main(string[] args)
{
var myDict = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
Console.ReadKey();
}
}
Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.
With C# 6.0, you can create a dictionary in the following way:
var dict = new Dictionary<string, int>
{
["one"] = 1,
["two"] = 2,
["three"] = 3
};
It even works with custom types.
You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
{ 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
{ 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
{ 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};
See How to initialize a dictionary with a collection initializer (C# Programming Guide) for details.
Suppose we have a dictionary like this:
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");
We can initialize it as follows.
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "Mohan" },
{ 2, "Kishor" },
{ 3, "Pankaj" },
{ 4, "Jeetu" }
};
Object initializers were introduced in C# 3.0. Check which framework version you are targeting.
Overview of C# 3.0
Note that C# 9 allows Target-typed new expressions so if your variable or a class member is not abstract class or interface type duplication can be avoided:
private readonly Dictionary<string, XlFileFormat> FILE_TYPE_DICT = new ()
{
{ "csv", XlFileFormat.xlCSV },
{ "html", XlFileFormat.xlHtml }
};
With ะก# 6.0
var myDict = new Dictionary<string, string>
{
["Key1"] = "Value1",
["Key2"] = "Value2"
};
Here is an example of Dictionary with Dictionary value
Dictionary<string, Dictionary<int, string>> result = new() {
["success"] = new() {{1, "ok"} , { 2, "ok" } },
["fail"] = new() {{ 3, "some error" }, { 4, "some error 2" } },
};
which is equivalent to this in JSON :
{
"success": {
"1": "ok",
"2": "ok"
},
"fail": {
"3": "some error",
"4": "some error 4"
}
}
The code looks fine. Just try to change the .NET framework to v2.0 or later.

Concise way to initialise a collection

I can initialise a class in a concise manner using something like:
public static readonly type TYPE_NAME = new type()
{
ClientIp = "ClientIp",
LanguageCode = "LanguageCode",
SessionToken = "SessionToken",
SystemKey = "SystemKey"
};
However is it possible to initialise a collection in a similar way (inherited from List<>)?
List<string> strList = new List<string>{ "foo", "bar" };
List<Person> people = new List<Person>{
new Person { Name = "Pete", Age = 12},
new Person { Name = "Jim", Age = 15}
};
Use a collection initializer
http://msdn.microsoft.com/en-us/library/bb384062.aspx
List<int> list = new List<int> { 1, 2, 3 };
Yes:
var l = new List<int>() { 1, 1, 2, 3, 5 };
You can surely use collection initializer.
To use this,
List<int> collection= List<int>{1,2,3,...};
To use collection initializer it need not to be exactly of List type.
Collection initializer can be used on those types that implements IEnumerable and has one public Add method.
You use Collection initializer feature even in the following type.
public class SomeUnUsefulClass:IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void Add(int i)
{
//It does not do anything.
}
}
Like,
SomeUnUsefulClass cls=new SomeUnUsefulClass(){1,2,3,4,5};
which is perfectly valid.

Categories

Resources