0

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.
T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 1
    If an int is 32 bits and uses all 32 bits than how do you distinguish the boolean values from the int values? Then do you create a 64 bit object and the int are 32 bit and the True and False are outside the 32 bit range? – jdweng Jun 24 '20 at 15:37
  • This answered by https://stackoverflow.com/questions/4537803/overloading-assignment-operator-in-c-sharp ... But I'm hesitant to call it duplicate... You may want to clarify your need and why you expect the assignment to behave as something else so someone may suggest workable aproach. – Alexei Levenkov Jun 24 '20 at 19:18
  • The implementation unique. You do not want the condition where 1 + 2 = 3 and 1 + 2 = 4. – jdweng Jun 24 '20 at 23:09

1 Answers1

2

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);
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Everything except very first line seem to be for some other question... "`dynamic myValue = smth ;` //if it is not either `int` nor `bool` then throw error. otherwise, continue script." – Alexei Levenkov Jun 24 '20 at 17:11