-1

I have a struct with several properties of varying types. I need a way to set all of them to values using a string to address the properties, I know I could use a Switch-Case statement but I was wondering if there is a faster/more elegant way to do it?

public struct ExampleStruct 
{
    public string exampleProperty1 {get; set; }
    public int exampleProperty2 {get; set; }
}
public class ExampleClass
{
    ExampleStruct e = new ExampleStruct();
    string s = "exampleProperty1";
    
    //
    // Is there a way to set exampleProperty1, using s to address it?
    // Something like e[s] = "foo"
    //
}
amelted
  • 3
  • 1

1 Answers1

0

You can use Type.GetProperty method for that as stated in documentation: https://learn.microsoft.com/en-gb/dotnet/api/system.type.getproperty?view=net-5.0

Type myType=typeof(ExampleStruct);
// Get the PropertyInfo object by passing the property name.
PropertyInfo myPropInfo = myType.GetProperty("exampleProperty1");
// Display the property name.
Console.WriteLine("The {0} property exists in ExampleStruct.", myPropInfo.Name);

Then, you can assign value like this:

string s = "exampleProperty1";
Type myType=typeof(ExampleStruct);
PropertyInfo myPropInfo = myType.GetProperty(s);
ExampleStruct e = new ExampleStruct();
myPropInfo.SetValue(e, "some value");

However, you maybe should try and find alternative solutions for your task, because using reflection for this is a little overkill.

e.e
  • 48
  • 4