4

I wanna define an object within some property, but I don't know how to do that. Like this:

var obj = ...;
obj["prop1"] = "Property 1";
obj["prop2"] = "Property 2";

And I can create a string to get one of them:

string temp = "prop1";
string prop1 = obj[temp];

Is it possible in C#?

6 Answers6

9

What you want is a dictionary:

var obj = new Dictionary<string, string>();

obj.Add("prop1", "Property1");

Console.WriteLine(obj["prop1"]);

If the properties are well defined, I would recommend creating a class:

public class MyObject
{
    public string Prop1;
    public string Prop2;
}

Then you can do things like:

var obj = new MyObject
{
    Prop1 = "Property 1",
    Prop2 = "Property 2"
};

Console.WriteLine(obj.Prop1); //Will echo out 'Property 1'
Blue
  • 22,608
  • 7
  • 62
  • 92
1
Dictionary<string,string> obj = new Dictionary<string,string>();
obj.Add("prop1","Property 1");
obj.Add("prop2","Property 2");

string temp = obj["prop1"];
dijkstra
  • 1,068
  • 2
  • 16
  • 39
1

What you are doing is called an indexer. You can add an indexer to classes. It usually takes 1 or more arguments.

Calling an indexer:

To call an indexer, you use an instance of that class and add [] at the end of the name. Then, add the arguments into the []. Let's take string as an example. In the string class, there is an indexer that takes a argument of type int. It gets the character at that index of the string.

char theFirstChar = someString[0];

The indexer can also take multiple arguments:

int[,] matrix = new int[10, 10]; //Note: This is not an indexer
int someValue = matrix[9, 4]; //This is

Syntax:

You define an indexer like this: (I used the string example)

public char this[int i]
{
    get
    {
        // code
    }
    set
    {
        // code
    }
}

It's very much like a property.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Dictionary, see https://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx at the bottom.

Daniel Bişar
  • 2,663
  • 7
  • 32
  • 54
0

The closest you get in C# is Dictionary<TKey, TValue>

Source: Set array key as string not int?

Community
  • 1
  • 1
0

It's called ExpandoObject in C#

see https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=c%23%20expandoobject

GreatAndPowerfulOz
  • 1,767
  • 13
  • 19