C# – Why is there no key specified with .NET KeyNotFoundException

cdictionarynet

Why is there no key specified with .NET KeyNotFoundException (in message/property)? Is it because of performance reasons? Is it because when Dictionary finds out there isnt any requested object by the hash it already doesnt know the context of the original key? I couldnt find an answer to this question anywhere.

Best Answer

This may not be the official answer, but...

C# and VB.NET - the main .NET languages - are statically typed languages(yea, I know, they support dynamic typing, but still). This means properties in classes are typed. What would the type of KeyNotFoundException.Key be?

Dictionary<string, string> dict1 = new Dictionary<string, string>();
try
{
    Console.WriteLine(dict1["one"]);
}
catch (KeyNotFoundException e)
{
    // is e.Key a string?
}

Dictionary<int, int> dict2 = new Dictionary<int, int>();
try
{
    Console.WriteLine(dict2[1]);
}
catch (KeyNotFoundException e)
{
    // is e.Key an int?
}

If you wanted to properly support this, you'd have to use generics - KeyNotFoundException<string> and KeyNotFoundException<int>. But this would complicate the API just so you can get information you already have.

Related Topic