Vladyslav  Kurkotov
Vladyslav Kurkotov

Reputation: 505

How to detect enum type passed to Enum[]

In my MVC project I have MyEnum:

public enum MyEnum
{
    a,
    b,
    c,
    d
}

I also have class:

public class MyClass
{    
    public MyEnum SelectType { get; set; }

    public Enum[] NotSupportedTypes{ get; set; }
}

In my class for NotSupportedTypes I can use only Enum[] type.

When I'm creating object of class MyClass how can I check that in NotSupportedTypes only enums of type MyEnum are pushed?

var model = new MyClass();

//good
model.NotSupportedTypes = new Enum[] { MyEnum.a }

//bad
model.NotSupportedTypes = new Enum[] { SomeOtherEnum.a }

Upvotes: 0

Views: 65

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460340

You could check it in the property, for example with Array.TrueForAll:

private Enum[] _NotSupportedTypes;
public Enum[] NotSupportedTypes
{
    get { return _NotSupportedTypes; }
    set {
        if (!Array.TrueForAll(value, x => x.GetType() == typeof(MyEnum)))
            throw new ArgumentException("All enums must be MyEnum");
        _NotSupportedTypes = value; 
    }
}

As mentioned by Xanatos this won't protect you from changes in the array. So you could replace one MyEnum in it with a different enum type later. Arrays are not readonly.

So why don't you use a MyEnum[] in the first place?

Upvotes: 1

Pawel Maga
Pawel Maga

Reputation: 5807

var model = new MyClass();

//good
//model.NotSupportedTypes = new Enum[] { MyEnum.a }

//bad
model.NotSupportedTypes = new Enum[] { SomeOtherEnum.a }

var validTypes = model.NotSupportedTypes.All(n => n.GetType() == typeof(MyEnum));

Upvotes: 0

Related Questions