Search code examples
c#refactoringcode-snippetscode-readabilityconditional-statements

Neatest/most idiomatic way to rewrite this If in C#


I have this if-else statement which does what I want. What it's doing is pretty straightforward as you should be able to tell.

if (width != null && height != null)
{
    if (top != null && left != null)
    {
        ret.type = VMLDimensionType.full;
    }
    else
    {
        ret.type = VMLDimensionType.size;
    }
}
else
{
    if (top != null && left != null)
    {
        ret.type = VMLDimensionType.positon;
    }
    else
    {
        ret.type = VMLDimensionType.unset;
    }
}

The enum being referred to is:

private enum VMLDimensionType
{
    unset = 0,
    full = 1,
    size = 2,
    position = 3
}

It's so straightforward I'm sure there's a much more terse and more readable way to express this.

NB If it wasn't for the ridiculous 'one-brace per line' rule that VS imposes by default I probably wouldn't be so bothered. Eg in VB I could lose about 10 lines from this code block! (any thoughts on that as an aside?)


Solution

  • One option would be to make VMLDimensionType a Flags enumeration:

    [Flags]
    enum VMLDimensionType
    {
        Unset = 0,
        Size = 1,
        Position = 1 << 1,
        Full = Size | Position
    }
    

    And then:

    ret.Type = VMLDimensionType.Unset;
    
    if(width != null && height != null)
        ret.Type |= VMLDimensionType.Size;
    
    if (top != null && left != null)
        ret.Type |= VMLDimensionType.Position;