c# modify a generic property -
i have viewmodel 2 properties of same type (bool). have function sets 1 of properties bool value. let's have isreadonly property.
public void setreadonly(myviewmodel vm, bool newval) { vm.isreadonly = newval; }
now want make more generic, , have function both:
public void setbooleanproperty(myviewmodel vm, bool newval, ?bool? myproperty) { vm.myproperty = newval; // sure error, myproperty doesn't exist in viewmodel. shows way have. }
i started approach:
public void setbooleanproperty<tprop>(myviewmodel vm, bool newval, tprop myproperty) { vm.??? = newval; }
i don't use function getpropertybyname("isreadonly") think available somewhere in reflection classes .net. reason: if developer refactors project , renames isreadonly, string wouldn't updated. there solutiuon ?
you're trying use reflection without using reflection. don't think you're going find answer. there no generics against properties in language.
closest thing can think of, awful, pass in action - pretty ridiculous, works. please don't this:
public void performaction(myviewmodel vm, bool newval, action<myviewmodel, bool> action) { action(vm, newval); } performaction(someviewmodel, true, (vm, b) => vm.isreadonly = b);