1

Why do I need to cast a generic type T to object first, before I can cast it to a bool?

Can I constraint T so that I can cast it to bool directly?

e.g.

    public void Set<T>(T value)
    {
        if (typeof (T) == typeof (bool))
        {
            Manager.SetValue(ID, (bool) (object) value);
        }
        // ...
    }
bas
  • 13,550
  • 20
  • 69
  • 146
  • Because `T` can be any `Type`, not only `bool`. That's the purpose of generic types. – Arghya C Oct 31 '15 at 20:50
  • 1
    That doesn't explain why I have to cast it to `object` before I am allowed to cast it to `bool`. I understand what generics are. – bas Oct 31 '15 at 20:51
  • Very good question! Jon Skeet answers your first question in another SO question, so I'm marking this one as a duplicate. As to your second question: Nope, such a constraint is not possible as far as I know. – Heinzi Oct 31 '15 at 20:54
  • @Heinzi google-d for this for quite a bit, care to link the answer? Thx in advance – bas Oct 31 '15 at 20:55
  • @bas: Just follow the link which is now at the top of your question, it's the first (and accepted) answer. – Heinzi Oct 31 '15 at 20:56
  • Right. Casting can be done only from compatible types or from object. As the type of T is not known, it cannot be casted directly to type 'X'. So `(X)value` will not work, while `(X)(object)value` will work. – Arghya C Oct 31 '15 at 20:56
  • @Heinzi, Jon Skeet always knows doesn't he :). But, that helps understanding, good to know that `as` operator will work as well. PS: sorry for the dumb comment, didn't refresh this page yet so didn't realise the link was there already – bas Oct 31 '15 at 21:02
  • Notice that `as` works only for reference types, so it will not work for `bool`. – Arghya C Oct 31 '15 at 21:04
  • @ArghyaC ah right, good one. – bas Oct 31 '15 at 21:05

0 Answers0