0

Sorry if the title is not clear, it was hard to properly word this question.

I have an object named Stuff and MoreStuff.

public class Stuff()
{
    public string Field1;
    public string Field2;
}

public class MoreStuff()
{
    public string Field3;
    public string Field4;
}

I want to create something that adds a value to Field1 when the string fieldValue = 'Field1'

To make it more clear, something like this. But I want to have it generic for any object.:

string fieldValue = 'Field1'
Stuff thing = new Stuff();
checkField(fieldValue);
thing.fieldValue = 'checked';

string fieldValue = 'Field4'
MoreStuff moreThing = new MoreStuff();
checkField(fieldValue);
moreThing.fieldValue = 'checked';   

Is this possible to do in C#? I can't find anything about it, also hard to search for a question like this.

KHcc
  • 89
  • 1
  • 2
  • 11
  • Use reflection, but this sounds like it may be an [X-Y problem](http://xyproblem.info/). – DavidG Oct 28 '15 at 14:05
  • You can use reflection to get the value of a field by name, however you can't just aribitrarily add fields to the object. You could do that with an ExpandoObject but not plain classes, at least not without IL weaving. – Ron Beyer Oct 28 '15 at 14:07
  • Possible duplicate of [C# setting/getting the class properties by string name](http://stackoverflow.com/questions/10283206/c-sharp-setting-getting-the-class-properties-by-string-name) – DavidG Oct 28 '15 at 14:07
  • Thanks, reflection was exactly what I was looking for. The adding of fields was just a bad example of me. – KHcc Oct 28 '15 at 14:09

2 Answers2

1

You can use reflection:

string fieldName = "Field1";
Stuff thing = new Stuff();

thing.GetType().GetField(fieldName).SetValue(thing, "checked");
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
1
Square test = new Square();
test.Field1 = "sdflsjf";
test.Field2 = "sdlfksj";
test.Field3 = "sldfjs";

foreach (PropertyInfo propertyInfo in test.GetType().GetProperties())
{
    if (propertyInfo.Name == "Field2")
        propertyInfo.SetValue(test, "checked");

}

This uses System.Reflection to do approximately what you're looking for by the sounds of it.

Mark E
  • 371
  • 2
  • 12