-2

I am trying to name a Person object with "objectName" as below but not succeeding, any help? How to do it?

string objectNameString = "objectName";
Person objectNameString = new Person();

I try to create a Person list from several user inputs, the names must be unique in list.

3 Answers3

0

Following should create new instance of Person using string from objectNameString.

string objectNameString = "Person";

var person = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(objectNameString );
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
0

If you want to use the value of the objectNameString variable, using a Dictionary or ExpandoObject is the closest you can get:

Dictionary<string, object> someObject = new Dictionary<string, object>();
someObject[objectNameString] = new Person();

Person p = (Person)someObject[objectNameString];

Or, if you only add Persons, the dictionary could look like Dictionary<string, Person>.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

I think I get your question. You have a string (e.g. from user input). And you want to create an Person which has the variable name of the string mentioned before.

Dictionary<string, Person> someObject = new Dictionary<string, Person>();
string objectNameString = "objectName";
someObject[objectNameString] = new Person();
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
coolerfarmer
  • 385
  • 2
  • 9
  • Hi, Yes you got it! I try to get it from user input. But what is that "someObject",where does it come from otherwise i understood the solution! – user3821069 Jul 09 '14 at 15:58