Best exception for an invalid generic type argument

后端 未结 11 1186
孤城傲影
孤城傲影 2020-12-08 18:21

I\'m currently writing some code for UnconstrainedMelody which has generic methods to do with enums.

Now, I have a static class with a bunch of methods which are

11条回答
  •  离开以前
    2020-12-08 18:40

    Generic programming should not throw at runtime for invalid type parameters. It should not compile, you should have a compile time enforcement. I don't know what IsFlag() contains, but perhaps you can turn this into a compile time enforcement, like trying to create a type that is only possible to create with 'flags'. Perhaps a traits class can help.

    Update

    If you must throw, I'd vote for InvalidOperationException. The reasoning is that generic types have parameters and errors related to (method) parameters are centered around the ArgumentException hierarchy. However, the recommendation on ArgumentException states that

    if the failure does not involve the arguments themselves, then InvalidOperationException should be used.

    There is at least one leap of faith in there, that method parameters recommendations are also to be applied to generic parameters, but there isn't anything better in the SystemException hierachy imho.

提交回复
热议问题