I have the following class example here:
public class Foo
{
public int Id { get; set; }
public string Bar { get; set; }
public string FooBar { get; set; }
public string Fizz { get; set; }
public string Buzz { get; set; }
public static Foo Create(int id, string property, string value)
{
return new Foo
{
Id = id,
};
}
}
Now, however, i want to set for example only Bar to a value in the Create method of the class if the propertyname is Bar . So i took a look at C# setting/getting the class properties by string name but i can't get this to work in the create method. Same goes for Setting a property by reflection with a string value so i'm kinda lost here.
As a small bit of clarification. I can get the above methods to work in the create, however not in the return which is where it needs to work.
The solution below seems to work for us for now, however, i think it could be optimized.
public class Foo
{
public int Id { get; set; }
public string Bar { get; set; }
public string FooBar { get; set; }
public string Fizz { get; set; }
public string Buzz { get; set; }
public static Foo Create(int id, string property, string value)
{
return new Foo
{
WebshopCustomerId = webshopCustomerId,
Bar = (typeof(Foo)).GetProperty(property).Name == "Bar" ? value : null,
FooBar = (typeof(Foo)).GetProperty(property).Name == "FooBar" ? value : null,
Fizz = (typeof(Foo)).GetProperty(property).Name == "Fizz" ? value : null,
Buzz = (typeof(Foo)).GetProperty(property).Name == "Buzz" ? value : null,
};
}
}