0

Is it possible to use a variable to access 2 variables without naming another variable?

For example, to:

LOG.dig.CNLog = 7;
LOG.value.CNLog = 17;

I would like to use something like this

string a = "dig";
string b = "value";
LOG.[a].CNLog = 7;
LOG.[b].CNLog = 17;

It's possible to use this? If yes what is the correct format?

Thanks

Cullub
  • 2,901
  • 3
  • 30
  • 47
  • 3
    Dictionary – BlackBear Aug 16 '14 at 16:33
  • A blog entry on creating a dynamic dictionary: http://reyrahadian.wordpress.com/2012/02/01/creating-a-dynamic-dictionary-with-c-4-dynamic/ – nullforce Aug 16 '14 at 16:52
  • Check this: [http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – Fabio Aug 16 '14 at 16:59
  • @nullforce Given that the OP's problem derives from not knowing the property's name at compile time, then the dynamic dictionary doesn't solve his issue. – dcastro Aug 16 '14 at 17:00
  • @nullforce What that blog gives which `ExpandoObject` doesn't have.? It shows how to reinvent `ExpandoObject`. – Sriram Sakthivel Aug 16 '14 at 17:01

2 Answers2

1

You can use a Dictionary<string, int>. An example:

var dict = new Dictionary<string, int>();
dict.Add("test", 1);
var testVal = dict["test"];
Grant H.
  • 3,689
  • 2
  • 35
  • 53
0

You can do that by using a Dictionary<TKey, TValue>.

A dictionary is a collection of keys and values. In your case you probably would like to use a Dictionary<string, LogClass> then you can have something like this:

Assuming LogClass is your class...

public class LogClass
{
    public int CNLog { get; set; }
}

string a = "dig";
string b = "value";

dictionary[a].CNLog = 7;
dictionary[b].CNLog = 17;

But of course before doing that you would have to say what is the value that goes into dictionary[var].

dictionary[a] = new LogClass();

That is how you would use it, hopefully you will be able to adapt this solution to your code.

And you can check out a video that explains step-by-step very slowly and clearly how to work with it on Microsoft Virtual Academy: C# Fundamentas at 22:00.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452