0

I have a list of strings in C# and I want to loop through the list and add each item of the list as a property of my class. For eg:

public class test
{
 List<string> inputList = new List<string> {"add", "subtract", "multiply"};
 foreach(var val in inputList)
 {
   //code to convert string to property
 }
}

After I run the above code, when I create a new object of class test, I would like to get: test.add or test.subtract etc. and I should be able to assign values to these properties.

Is this possible? If yes, could someone please suggest the best way of doing this?

Continuing from above, the aim here is to add API. The list here is dynamically loaded. I should have started with a more apt list as an example.

public class test
    {
     List<string> inputList = new List<string> {"name", "age", "dob"};
     foreach(var val in inputList)
     {
       //code to convert string to property of the class test
     }
    }

After the code is run I should be able to assign values to name, age and dob as user inputs i.e

test.name = "blah"
test.age = "123"

Since the list is dynamically updated, the items (and their number) in the list will vary. All the items in the list have to be added as a property of the class test and the user should be able to assign values to those properties at run time.

DevL
  • 1
  • 1
  • 3
    Can you please show the actual data-structure you want to create? Do you have a class whose properties you want to set dynamically? Or is this some in-memory key-value-like data-structure like a `Dictionary`? – MakePeaceGreatAgain Jan 23 '20 at 11:07
  • 2
    Have a look at `ExpandoObject` and `DynamicObject` – Dmitry Bychenko Jan 23 '20 at 11:10
  • https://stackoverflow.com/questions/3862226/how-to-dynamically-create-a-class – mastermind Jan 23 '20 at 11:31
  • @SaniSinghHuttunen I am not looking to create a new class at run time. Instead, I want to expand the existing class (test in this case) at run time by adding property(s) to it. – DevL Jan 23 '20 at 12:06
  • @HimBromBeere I do have a class for which I want to create properties dynamically and then allow the user to set value for these properties. – DevL Jan 23 '20 at 16:35

1 Answers1

1

You can use dynamic to achieve this. While it's very good to be aware of the concept of dynamic and how to use it, it kills the benefits of using a strongly typed language and compile time checking, and should really only be used when the alternative is more painful:

List<string> inputList = new List<string> {"add", "subtract", "multiply"};

var builder = new System.Dynamic.ExpandoObject() as IDictionary<string, Object>;

foreach(var val in inputList)
{
   builder.Add(val, $"{val}: some value here"); 
}   

var output = (dynamic)builder;

Console.WriteLine(output.add);
Console.WriteLine(output.subtract);
Console.WriteLine(output.multiply);
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112