Generic functions and ref returns in C# 7.0 -
is possible use ref returns feature in c# 7.0 define generic function can both comparison , update of field in 2 instances of object? imagining this:
void updateifchanged<tclass, tfield>(tclass c1, tclass c2, func<tclass, tfield> getter) { if (!getter(c1).equals(getter(c2)) { getter(c1) = getter(c2); } }
example intended usage:
thing thing1 = new thing(field1: 0, field2: "foo"); thing thing2 = new thing(field1: -5, field2: "foo"); updateifchanged(thing1, thing2, (thing t) => ref t.field1); updateifchanged(thing1, thing2, (thing t) => ref t.field2);
is there way specify func type or kind of generic type restriction make valid requiring getter return reference? tried func<tclass, ref tfield>
, doesn't appear valid syntax.
you won't able use func
, because doesn't return result reference. you'll need create new delegate uses ref return:
public delegate ref tresult refreturningfunc<tparameter, tresult>(tparameter param);
then changing function use delegate enough work:
public static void updateifchanged<tclass, tfield>(tclass c1, tclass c2, refreturningfunc<tclass, tfield> getter) { if (!getter(c1).equals(getter(c2))) { getter(c1) = getter(c2); } }
note property cannot returned reference. return field reference, or other variable, property not variable.
Comments
Post a Comment