0

I'm creating a styling system for my UI with a set of StyleRule's for each UI type. Such as an ImageStyleRule in which you can set what image to show, with what color etc. Every property also needs to be optional, or Overridable. Leaving the property null isnt enough because in that case i cannot distinguish between set-this-field-to-null and leave-this-field-alone.

My setup looks like this:

public class Overridable<T>
{
    public T Value;
    public bool Override;
}

public class ImageStyleRule : StyleRule<Image>
{
    private Overridable<Sprite> sprite = null, overrideSprite = null;
    private Overridable<Color> color = null;
    private Overridable<Material> material = null;

    public override void ApplyRule(Image element)
    {
        base.ApplyRule(element);

        if (sprite.Override)
            element.sprite = sprite.Value;
        if (overrideSprite.Override)
            element.overrideSprite = overrideSprite.Value;

        if (color.Override)
            element.color = color.Value;

        if (material.Override)
            element.material = material.Value;
    }
}

As you can see the ApplyRule method contains a lot of duplicate code, and i'd really like to avoid that. I think i need a method like this: setOverride(*element.sprite, sprite) where i pass in the field and a reference to the Overridable and it magically sets the right reference.

I've tried passing by reference, and using pointers but none work. Reflection would be too slow for my use case. Is there any other way to solve this issue?

Thanks in advance!

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
  • 1
    You *really* shouldn't have mutable structs. Your code also doesn't compile as is. – Servy Feb 02 '18 at 20:11
  • @Servy Changed the struct to a class, like it is in the codebase. I dont think its a duplicate because i'm not trying to get a reference, i'm trying to set it. The only compilation errors are the missing base classes, which i dont think are relevant at all. I have the feeling like it should be possible with unsafe code. – TJHeuvel Feb 02 '18 at 20:24
  • @Servy Since you aren't dealing with properties, it really isn't a duplicate. And for non-properties, that answer is out of date. – NetMage Feb 02 '18 at 20:32
  • @TJHeuval Are you using c# 7.0? You can pass `ref` to class fields. I have an answer, but have to see if the question is unblocked. – NetMage Feb 02 '18 at 20:41
  • @NetMage Thanks a lot for thinking with me! I could upgrade if this is a proper fix. I had been looking at the changes too. If this stays closed i might re-ask it. – TJHeuvel Feb 02 '18 at 20:45
  • 2
    @TJHeuvel The duplicate *isn't* about getting a property, it *is* about setting it. You most certainly don't want to be touching unsafe code. It won't help you, and you wouldn't want to use it even if it would. – Servy Feb 02 '18 at 20:50

0 Answers0