views:

246

answers:

2

Say I want to loop through a datareader and create a load of objects of a certain type but using a value from the datareader as the object name e.g.

String "string_" + <value from datareader> = new String();

So if I had values temp1,temp2 & temp3 coming out of the datareader I would have 3 new objects of type string e.g.

string_temp1
string_temp2
string_temp3

How can I create the objects with the name from the datareader?, or is there any suggestions on a better way to do this?

+10  A: 

Rather than using reflection, I think it'd be easier to just use a Dictionary that maps the names you want the objects to have to their values:

var map = new Dictionary<String, String>();
map[...] = new String();
//   ^
//   |
//   +---- substitute with whatever naming scheme you deem suitable
John Feminella
This is definately a good approach to the problem.
Statement
Kill the useless `string_` prefix though.
Konrad Rudolph
This is definitely the way to go. :)
ionut bizau
@Konrad: I was emulating his example, but you're right that there isn't a point to this. Boo Hungarian-ish prefixes! Removed.
John Feminella
+1  A: 

There would be little value in doing this. If you create the variable NAME from the value, there would be no way to reference that variable in your code following this, since the code is compiled at compile time, and you're trying to set variable names at runtime.

Remember, variable names are really just there for the compiler to be able to map into IL, and eventually JIT correctly. This is why obfuscation works - one of the main things most obfuscators do is scramble all of your variable names into very short, meaningless names. This has no effect on runtime behavior - the names are meaningless once compiled.

I'd recommend going with John Feminella's approach, or something similar.

Reed Copsey