I am implementing an IDictionary interface, which has parameter object
for its get
set
.
object this [object key] { get; set; }
I want to enforce the key to be type of string, so in my code I do:
(if key.GetType() != typeof(string)) {
//
}
I want to throw an exception when this happen. However I don't know what the most appropriate exception to use in this case. The closest one I can find is TypeInitializationException and ArgumentException. However, it is stated in this document: "Do throw System.ArgumentException or one of its subtypes if bad arguments are passed to a member", which makes me wonder if mine is the right use case for it.
What should I use my case? Should I use Assert instead of throwing Exception?
ArgumentException
is the correct exception. The entire BCL uses it and so should you. TypeInitializationException
does not fit at all. It has one use case only: a throwing static ctor.
That said, if you are not producing a library (just internal code) you can deviate from that convention if there is a good reason. If you want to use a Debug.Assert
or some alternative, feel free to do it.
First I think, the best solution is Mathhew's; Why you just not using the Generic dictionary of type string.
If you need to apply the other approach than Code Contracts is the best way to do that.
Example: Contract.Requires(key is string); etc. Assert is not suitable for this problem but ArgumentException can be applied.
Thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With