473,800 Members | 2,418 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dictionary class lacks the very basic function ?

I want to use Dictionary class like this:

textboxM.Text = oMyDict.GetValu e("textboxM") ;
textboxN.Text = oMyDict.GetValu e("textboxN") ;

Where my dictionary contains the list of values for my textbox based on
the textbox id.

But it doesn't have it !

TryGetValue !? What's that ? Why I have to provide an out parameter,
isn't more simple just return the value or null if not found !?

Sep 22 '06 #1
3 1602

craigkeniss...@ hotmail.com wrote:
TryGetValue !? What's that ? Why I have to provide an out parameter,
isn't more simple just return the value or null if not found !?
What if "null" is actually the value corresponding to that key?
Example:

Dictionary Dict = new Dictionary();
Dict.Add("key", null);

Now, using your preferred method, the call would be something like:

object value = Dict["key"];

How do you know if it was there or not? In this situation (i.e. the
function -returns- the value), the only way to know is to have the
function (the indexer) throw an exception if it's not found. And in
fact, Dictionary does throw an exception if an entry with the key you
specified is not found. TryGetValue is useful though in a situation
where there is a chance the key might not be there.

object value;
bool Result = Dict.TryGetValu e("key", out value);
if (!Result)
{
//The key wasn't in the dictionary.
}
In the first situation, where you use the indexer, it's still possible
to guarantee no exception will be thrown if you use code like this:

if (Dict.ContainsK ey("key"))
object value = Dict["key"];

But performance suffers now, because you are doing -two- separate
lookups into the hash table. One for ContainsKey, then doing the exact
same lookup again to fetch it.

I admit, using out parameters feels clunky sometimes and inelegant, but
in this case it is the most elegant and performance efficient way to
handle everything with one function call.

Sep 22 '06 #2
>I want to use Dictionary class like this:
>
textboxM.Tex t = oMyDict.GetValu e("textboxM") ;
textboxN.Tex t = oMyDict.GetValu e("textboxN") ;

Where my dictionary contains the list of values for my textbox based on
the textbox id.

But it doesn't have it !
Use the indexer

textboxM.Text = oMyDict["textboxM"];

>TryGetValue !? What's that ? Why I have to provide an out parameter,
isn't more simple just return the value or null if not found !?
A Dictionary can be instantiated with a value type that isn't
nullable, so returning null isn't always an option. That's why
TryGetValue is needed.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Sep 22 '06 #3
I ended up writing a variation of Dictionary class:

public class StringDictionar y : Dictionary<stri ng, string>
{

public string GetValue(string key)
{
string outvalue;

if (this.TryGetVal ue(key, out outvalue) == false)
{
outvalue = "";
};

return outvalue;
}

}

So, simple !

Thanks you all !

Sep 22 '06 #4

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

Similar topics

2
1666
by: Tobias Pfeiffer | last post by:
Hi! Damnit, am I angry! Please look at the following example: class bla: def __init__(self): self.ho = {'a': , 'c': , 'b': , 'e': , 'd': , 'g': , 'f': , 'h': } # shall be an adjacence list of a graph... self.oha =
4
2524
by: brianobush | last post by:
# # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I want to # init a class from that dictionary. # However, I don't want to specify the # dictionary gets by hand # since it is error prone.
125
7237
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
1
9263
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex DataBinding accepts as a data source either an IList or an IListSource at System.Windows.Forms.ListControl.set_DataSource(Object value)
1
4519
by: Martin Widmer | last post by:
Hi Folks. When I iterate through my custom designed collection, I always get the error: "Unable to cast object of type 'System.Collections.DictionaryEntry' to type 'ContentObjects.ContentBlock'." The error occurs at the "For...Each" line if this method:
7
2070
by: noro | last post by:
Is it possible to do the following: for a certain class: ---------------------------- class C: def func1(self): pass def func2(self):
8
3114
by: akameswaran | last post by:
I wrote up a quick little set of tests, I was acutally comparing ways of doing "case" behavior just to get some performance information. Now two of my test cases had almost identical results which was not at all what I expected. Ultimately I realized I don't really know how literals are treated within the interpreter. The two implementations I was looking at were: class caseFunction(object): def __init__(self):
20
34164
by: Gustaf | last post by:
This is two questions in one really. First, I wonder how to convert the values in a Dictionary to an array. Here's the dictionary: private Dictionary<Uri, Schemaschemas = new Dictionary<Uri, Schema>(); Uri is the System.Uri class, and Schema is a class I made. Now, I want the class where this Dictionary is contained to have a property that returns all the values in this Dictionary. Like such: public Schema Schemas
0
187
by: Calvin Spealman | last post by:
On Thu, Jul 17, 2008 at 7:45 AM, mk <mrkafk@gmail.comwrote: As was pointed out already, this is a basic misunderstanding of assignment, which is common with people learning Python. To your actual problem... Why do you wanna do this anyway? If you want to change the function in the dictionary, why don't you simply define the functions you'll want to use, and change the one you have bound to the key in the dictionary when you want to...
0
9551
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10033
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7576
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5471
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.