Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use exception for type mismatch in C#

Tags:

c#

exception

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?

like image 445
bizi Avatar asked Aug 22 '13 20:08

bizi


2 Answers

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.

like image 133
usr Avatar answered Oct 02 '22 08:10

usr


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

like image 22
Bassam Alugili Avatar answered Oct 02 '22 06:10

Bassam Alugili