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?

1
  • I have a need to do this as well, only I need object types (not strings) with variable names defined at runtime. I need this to satisfy DataContractSerializer for a legacy web service, where the element name is also the identifier. I don't think any of the answers below satisfy the OP question. Commented Jul 15, 2014 at 16:52

2 Answers 2

11

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
Sign up to request clarification or add additional context in comments.

3 Comments

Kill the useless string_ prefix though.
This is definitely the way to go. :)
@Konrad: I was emulating his example, but you're right that there isn't a point to this. Boo Hungarian-ish prefixes! Removed.
2

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.

Comments