4

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 !

3 Answers 3

11
public Dictionary<string, string> s;

MSDN documentation

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I would suggest it too.
@StefanP. If it works then mark that answer as the correct one.
4

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"]);

Comments

2

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.