473,372 Members | 924 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 software developers and data experts.

Overriding Dictionary Not Found Exception

Is it possible to override the behaviour of a dictionary if an object is not
found?

string ss=null;
Dictionary<string, string> dict = new Dictionary<string,
string>();

// method 1

try { ss = dict["x"]; }
catch (KeyNotFoundException) {/* Ignore */}

// method 2

if (dict.ContainsKey("x")) ss = dict["x"];

In Method 1, if the key is not there then we have the considerable overhead
of an Exception.
In Method 2 it looks as though we need two dictionary scans.

So is it possible to change the default behaviour of a dictionary so it
returns a null value if not found rather than throwing the exception?

--
Paul
Dec 21 '05 #1
9 6787
Hello!

The Dictionary class is not sealed, so you could create a new concrete
Dictionary with the new functionality. The indexer is not marked virtual, so
you would have to use the "new" keyword when defining the new indexer (you
should make sure that all apropriate methods are re-implemented to ensure
the null-behaviour you're looking for).

Another approach would be to use the Dictionary.TryGetValue() method instead
and adapt your client code to the default non-null behaviour.

--
With regards
Anders Borum / SphereWorks
Microsoft Certified Professional (.NET MCP)
Dec 21 '05 #2
You can use TryGetValue instead.

string ss=null;
Dictionary<string, string> dict = new Dictionary<string,
string>();

if (dict.TryGetValue("x", out ss) == true) {
/* the key was found, and ss now contains the value */
} else {
/* the key wasn't found, and ss is null */
}

Jesse

Dec 21 '05 #3
<=?Utf-8?B?UGF1bHVzdHJpb3Vz?= <msdn_whoisat_paulcotter.com>> wrote:
Is it possible to override the behaviour of a dictionary if an object is not
found?

string ss=null;
Dictionary<string, string> dict = new Dictionary<string,
string>();

// method 1

try { ss = dict["x"]; }
catch (KeyNotFoundException) {/* Ignore */}

// method 2

if (dict.ContainsKey("x")) ss = dict["x"];

In Method 1, if the key is not there then we have the considerable overhead
of an Exception.
In Method 2 it looks as though we need two dictionary scans.

So is it possible to change the default behaviour of a dictionary so it
returns a null value if not found rather than throwing the exception?


You could use Dictionary.TryGetValue - it looks like that's what you're
after.

From a pragmatic (but not elegant) point of view, are you sure that
catching the exception *actually* incurs an overhead which is
significant in your application? You might be surprised just how cheap
exceptions are. See
http://www.pobox.com/~skeet/csharp/exceptions.html for some discussion
on this. I only mention this because many people have bought into the
mantra of "exceptions are expensive" without really looking into it.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 21 '05 #4
To All Above... Thanks - next time I will read ALL the methods before
posting. (As an excuse - it IS the last one in the method list :)

To Anders Borum.. TryGetValue is what I need, but I'll give yours a go as a
learning exercise.

--
Paul
Dec 21 '05 #5
HI,

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
I only mention this because many people have bought into the
mantra of "exceptions are expensive" without really looking into it.


I will read you article, but regarding the cost of an exception IIRC even
MS offer that view , that exception are expensive.

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Dec 21 '05 #6
Jon wrote:
http://www.pobox.com/~skeet/csharp/exceptions.html for some discussion
on this. I only mention this because many people have bought into the
mantra of "exceptions are expensive" without really looking into it.


Very interesting article. My experience has been that the *first* time
an exception is thrown it seems to take a few seconds (presumably
because it has to jit compile the assembly that contains the exception
type), but after that, if the *same* exception is thrown there is
practically no performance hit.

I wonder if there is a way to "pre-load" the exception types during the
start up of the app or is it even worth doing it.

Dec 21 '05 #7
Chris Dunaway <du******@gmail.com> wrote:
http://www.pobox.com/~skeet/csharp/exceptions.html for some discussion
on this. I only mention this because many people have bought into the
mantra of "exceptions are expensive" without really looking into it.


Very interesting article. My experience has been that the *first* time
an exception is thrown it seems to take a few seconds (presumably
because it has to jit compile the assembly that contains the exception
type), but after that, if the *same* exception is thrown there is
practically no performance hit.

I wonder if there is a way to "pre-load" the exception types during the
start up of the app or is it even worth doing it.


Have you experienced that when running a release build not in the
debugger? Do you have a complete program which demonstrates that? I've
only seen that happen in the debugger, which is a very different
situation.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 21 '05 #8
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
dot.state.fl.us>> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
I only mention this because many people have bought into the
mantra of "exceptions are expensive" without really looking into it.


I will read you article, but regarding the cost of an exception IIRC even
MS offer that view , that exception are expensive.


They're expensive if you're going to end up throwing them thousands and
thousands of times per second - otherwise they're almost always lost in
the noise.

As for whether or not to just follow MS's advice - I tend to trust the
evidence of my own eyes above MSDN. After all, it was only after
badgering them for quite a while that MSDN was changed to admit that
System.Decimal was a floating point type. (It had previously been
inaccurately described as a fixed point type.) MS are just as capable
of making mistakes as the rest of us :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 21 '05 #9
On 21 Dec 2005 06:47:33 -0800, "Chris Dunaway" <du******@gmail.com>
wrote:
Jon wrote:
[snip]
I wonder if there is a way to "pre-load" the exception types during the
start up of the app or is it even worth doing it.


Presumably you could explicitly throw it yourself:

try {
throw new myPreLoadException();
}
catch (myPreLoadException) { /* Do nothing */ }

Whether it is worth doing is another question.

rossum
--

The ultimate truth is that there is no ultimate truth
Dec 28 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: callmebill | last post by:
I'm having a tough time figuring this one out: class MyKBInterrupt( ..... ): print "Are you sure you want to do that?" if __name__ == "__main__": while 1: print "Still here..."
26
by: Alan Silver | last post by:
Hello, I have a server running Windows Server 2003, on which two of the web sites use the MegaBBS ASP forum software. Both sites suddenly developed the same error, which seems to be connected to...
4
by: TS | last post by:
i have a class that i'm trying to understand that overrides BaseApplicationException's methods as follows. What i dont' understand is that i have never seen the inherit ":" on a method signature,...
2
by: jg | last post by:
I was trying to get custom dictionary class that can store generic or string; So I started with the example given by the visual studio 2005 c# online help for simpledictionay object That seem...
0
by: Ralf Gedrat | last post by:
Hello! I have a Application, this throws after some time following exception: Item has already been added. Key in dictionary: "- 1" key being added: "- 1" I use Application.Run with...
7
by: wardm | last post by:
I have created a Dict object in a C++ App that calls (embedded) Python functions. The Dict is to be used to pass variable data between the C++ App and the python functions. However I cannot get...
9
by: KraftDiner | last post by:
I have a dictionary and sometime the lookup fails... it seems to raise an exception when this happens. What should I do to fix/catch this problem? desc = self.numericDict KeyError: 589824 ...
3
by: craigkenisston | last post by:
I want to use Dictionary class like this: textboxM.Text = oMyDict.GetValue("textboxM"); textboxN.Text = oMyDict.GetValue("textboxN"); Where my dictionary contains the list of values for my...
10
by: r035198x | last post by:
The Object class has five non final methods namely equals, hashCode, toString, clone, and finalize. These were designed to be overridden according to specific general contracts. Other classes that...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.