Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / March 2008

Tip: Looking for answers? Try searching our database.

modify dictionary value

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Jon Slaughter - 17 Mar 2008 20:22 GMT
How do I modify the value of a dictionary object?

I have something like

Dictionary<string, A> Q = ...

Where A is a struct.

I want to change some values in A but

Q["somestr"].x = 1;

doesn't work because it makes them read only.

If I do something like

A a = Q["somestr"];

a.x = 1;

then of course it doesn't update the value in the dictionary.

The only way I know to do it is remove the key and then re-add it with the
new value... but surely there is a better way?
Jon Skeet [C# MVP] - 17 Mar 2008 20:37 GMT
> How do I modify the value of a dictionary object?
>
[quoted text clipped - 20 lines]
> The only way I know to do it is remove the key and then re-add it with the
> new value... but surely there is a better way?

No - or at least not without a bit of jiggery-pokery with interfaces.
But then it's a bad idea to make the struct mutable in the first place.
This is just one of the places where mutable structs are painful. Avoid
them, avoid them, avoid them.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Jon Slaughter - 17 Mar 2008 21:50 GMT
>> How do I modify the value of a dictionary object?
>>
[quoted text clipped - 26 lines]
> This is just one of the places where mutable structs are painful. Avoid
> them, avoid them, avoid them.

I moved on to a keyed collection. Thats actually what I originally wanted
but didn't know it existed. (a little easier than using a dictionary because
my value was a struct in the first place).

I changed the struct to a class though so I can easily modify the values.

Thanks,
Jon

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.