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"]);
Igli Kadija
  • 113
  • 2
  • 11

1 Answers1

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.

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260