1

I was wondering if I can add some variables in an array, and access them in a simply way like :

string[] ArrayName = {
    string abc;
    string varName;
}

//and later access them like:
Console.WriteLine(ArrayName[ab+"c"]);
2
  • 2
    Look into the Dictionary class. Commented Jul 18, 2013 at 23:23
  • 1
    Use Generic Collections to achieve something like this. Commented Jul 18, 2013 at 23:30

1 Answer 1

5

I think you're just looking for a dictionary:

var ArrayName = new Dictionary<string, string> {
    { "abc", "something" },
    { "varName", "something" },
};

Console.WriteLine(ArrayName["ab"+"c"]);

First Edit

Alternatively, as you may be aware, C# lets you overload operators like the indexer -- so if you wanted to, you could write a class that defines its own special behavior for obj["string"] (returning a member of the same name, or whatever else).

public class IndexableClass
{
    private string _abc = "hello world";

    public string VarName { get; set; }

    public string this[string name]
    {
        get 
        {
        switch (name)
        {
            // return known names
            case "abc" : return _abc;

            // by default, use reflection to check for any named properties
            default : 
                PropertyInfo pi = typeof(IndexableClass).GetProperty(name);
                if (pi != null) 
                {
                    object value = pi.GetValue(this, null);
                    if (value is string) return value as string;
                    else if (value == null) return null;
                    else return value.ToString();
                }

                // if all else fails, throw exception
                throw new InvalidOperationException("Property " + name + " does not exist!");
        }
        }
    }
}

static void Main()
{
    var ArrayName = new IndexableClass();
    Console.WriteLine(ArrayName["ab" + "c"]);
}

Second Edit

There are also anonymous types (var ArrayName = new { abc = "something" };), and dynamic types, which you may find useful.

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

3 Comments

Doesn't the initialization need parentheses? <string, string>() {
@AustinBrunkhorst actually parentheses are optional when you have the inline initialization { }.
Good to know, wasn't positive on it.

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.