Home > Software engineering >  Set a field value depending on itself and other fields
Set a field value depending on itself and other fields

Time:11-15

I want an Enum Field that can be set either to its own value if it is not null or depending on another member value.

I'm trying to do something like this:

public class Test {
    public bool Foo { get; set; } = false;
    public TypeEnum Bar {
            set
            {
                Bar =  Bar ?? (Foo ? TypeEnum.Type1 : TypeEnum.Type2);
            }
    }
}

CodePudding user response:

What I think Jeroen was proposing in comment:

public class Test 
{
    public bool Foo { get; set; } = false;
    public TypeEnum? Bar { get; private set; }
    public void SetBarDependingOnFoo()
    {
        Bar =  Bar ?? (Foo ? TypeEnum.Type1 : TypeEnum.Type2);
    }
}

That would be a one-time-set, though, because it will keep the value once it is not null any more.

Of course you could write a custom setter on Foo, that resets Bar to null ... but now I am speculating on what you want.

Another way to do this would be a little different with a little different behaviour:

public class Test 
{
    public bool Foo { get; set; } = false;
    public TypeEnum Bar => Foo ? TypeEnum.Type1 : TypeEnum.Type2;
}

Here, the Value of Bar always depends on the current state of Foo.


Let say Foo cannot be muted after set.

In that case, I'd question that this class makes sense, really. You may be wanting more of a "builder"...

public interface IBarBuilder
{
    IBarBuilder WithFoo(bool foo);
    TypeEnum Build();
}

public class BarBuilder: IBarBuilder
{
    private bool _myFoo = false;

    IBarBuilder IBarBuilder.WithFoo(bool foo)
    {
         _myFoo = foo;
         return this;
    }

    TypeEnum IBarBuilder.Build()
    {
         return _myFoo ? TypeEnum.Type1 : TypeEnum.Type2;
    }
}

Usage

var builder = new BarBuilder().WithFoo(true);
TypeEnum myBar = builder.Build(); // from here use myBar

Or even much simpler (I assumed your actual usecase may be more complex): a factory method ("factory" is a little exagerated here):

public static TypeEnum GetBar(bool foo) => foo ? TypeEnum.Type1 : TypeEnum.Type2;
  • Related