DevL
DevL

Reputation: 1

Is it possible to create a property from a string in C#?

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.

Upvotes: 0

Views: 99

Answers (1)

Jonesopolis
Jonesopolis

Reputation: 25370

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);

Upvotes: 1

Related Questions