Click here to Skip to main content
11,496,146 members (457 online)
The site is currently in read-only mode for maintenance. Posting of new items will be available again shortly.
See more: C#4.0 socket Dictionary
How can a dictionary be sent to the client From Server ?

I want to do I send the following dictionary

Dictionary rates = new Dictionary<string,>(); 
        rates.Add("usd", 47.5); 
        rates.Add("eur", 60.4);
        rates.Add("ukp", 78.8);

Codes do not work.Where is my problem? Whether this approach is wrong ?

Please show me the correct code

code in server :

public void GetListn()
        var dataToSend = new DataToSend { Rates = new Dictionary<string,>() };
        dataToSend.Rates.Add("asd", decimal.Parse("12.23"));
        dataToSend.Rates.Add("asd", decimal.Parse("41.11"));
        dataToSend.Rates.Add("asd", decimal.Parse("25.23"));
        var stream = new MemoryStream();
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, dataToSend.Rates);

public class DataToSend
    public Dictionary<string,> Rates { get; set; }

code in Client :

private void WindowLoaded(object sender, RoutedEventArgs e)
            _server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _data = new byte[BufferSize];
            _recv = _server.Receive(_data);
            var stream = new MemoryStream(_server.Receive(_data));
            var formatter = new BinaryFormatter();
            var dataToSend = (DataToSend)formatter.Deserialize(stream);
        catch (Exception exception)
            MessageBox.Show(exception.Message, "Error", MessageBoxButton.OK,
    public class DataToSend
        public Dictionary<string,> Rates { get; set; }
Posted 10-Nov-11 8:45am
Edited 10-Nov-11 9:43am
your code should work, if you are sending using TCP protocol then dictionary object stream should work only thing is at receiver you have to return back to dictionary object. you can use TCP Serialization.

If its HTTP then you can use HTTP Serialization but only thing on receiver side you need to have same Class to marshal the stream back to Object.
In your case, with strings it should work without any problem.

How about:
var dataToSend = new DataToSend { Rates = new Dictionary<string,>() };
dataToSend.Rates = (DataToSend)formatter.Deserialize(stream);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 10,401
1 OriginalGriff 8,910
2 Sascha Lefèvre 3,899
3 Maciej Los 3,422
4 Richard Deeming 2,600

Advertise | Privacy | Mobile
Web02 | 2.8.150520.1 | Last Updated 10 Nov 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100