Reputation: 331
In my code i declared like this :
public string[] s ;
and i need to use this string like this :
s["Matthew"]="Has a dog";
s["John"]="Has a car";
when i use s["Matthew"] an error appears and it says "Cannot implicitly convert 'string' to 'int'" . How can I make a string array to have string index ? if i write this in php it works :
array() a;
a["Mathew"]="Is a boy";
I need it to work also in asp.net !
Upvotes: 4
Views: 6521
Reputation: 1126
Array works on indexes and indexes are in numbers but you are passing string that's why you are getting error, @Christian suggest you to use Dictionary
Dictionary<string, string> dict = new Dictionary<string, string>()
{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
};
// retrieve values:
foreach (KeyValuePair<string, string> kvp in dict)
{
string key = kvp.Key;
string val = kvp.Value;
// do something
}
Upvotes: 2
Reputation: 8227
In C#, you cannot access an array element using, as array index, a string. For this reason you have that cast error, because the index of an array is, by definition of an array, an integer.
Why don't you use a data structure like a dictionary?
var dict = new Dictionary<string,string>();
dict.Add("John","I am John");
//print the value stored in dictionary using the string key
Console.WriteLine(dict["John"]);
Upvotes: 4