Search code examples
c#.net-4.5

How to create dynamic type variable which will accept only number and bool?


How can I create the dynamic type which will only accept bool and int?

I know this can be done manually by :

if ( smth is bool || smth is int){
    dynamic myValue = smth;
}

however, can I create a type which will avoid me the manually checking, so i could directly:

dynamic myValue = smth ;   //if it is not either `int` nor `bool` then throw error. otherwise, continue script.

Solution

  • You could define a custom type that accepts only a bool or an int:

    public readonly struct Custom
    {
        public readonly bool _bool;
        public readonly int _int;
    
        public Custom(bool @bool)
        {
            _bool = @bool;
            _int = default;
        }
    
        public Custom(int @int)
        {
            _bool = default;
            _int = @int;
        }
    }
    

    Then this would work:

    dynamic b = true;
    Custom custom = new Custom(b);
    

    ...but this would throw an exception at runtime:

    dynamic s = "abc";
    Custom custom = new Custom(s);