Use exception for type mismatch in C #

I am implementing an IDictionary interface that has an object parameter for its get set .

 object this [object key] { get; set; } 

I want the key to be a string type, so in my code, I:

 (if key.GetType() != typeof(string)) { // } 

I want to make an exception when this happens. However, I do not know which is the most suitable exception to use in this case. The closest I can find is TypeInitializationException and ArgumentException . However, this document states : "Do throw System.ArgumentException or one of its subtypes if bad arguments are passed to the member", which makes me wonder if the right use case is right for me.

What should I use in my case? Should I use Assert instead of throwing an Exception?

+6
source share
2 answers

ArgumentException is the correct exception. All BCL uses it, and so do you. TypeInitializationException not suitable at all. It has only one use case: throwing static ctor.

However, if you do not create a library (only internal code), you can deviate from this agreement if there is a good reason. If you want to use Debug.Assert or an alternative, feel free to do it.

+5
source

At first I think the best solution is Matthew; Why don't you just use a Generic dictionary like string.

If you need to take a different approach than the best option for this, use Code Contracts.

Example: Contract.Requires (key is a string); etc. Assert is not suitable for this problem, but an ArgumentException may apply.

thanks

+3
source

Source: https://habr.com/ru/post/952314/


All Articles