user584018
user584018

Reputation: 11304

how to design a class that where I can store and retrieve data using class properties/method

I would like to do something like below where I should be able to store and retrieve data though class properties or method,

 //set the value
        var someObject = {... };

        var newMessage = new Message(JsonConvert.SerializeObject(someObject))
        {
            ContentType = "application/json"
        };

        //get the value
        Message message;
        var x = message.GetBody<string>()

I tried creating class like below, but have to supply body for method. How to design this class?

public class Message
{
    public Message(object serializableObject);
    public string SessionId { get; set; }
    public string ContentType { get; set; }

    public T GetBody<T>();
}

Upvotes: 1

Views: 59

Answers (1)

Svek
Svek

Reputation: 12858

I think I understand your question, but you've missed out on the constructor

new Message(JsonConvert.SerializeObject(someObject)) //<-- string is passed

I think you have misinterpreted the JsonConvert.SerializeObject(someObject) statement, it will return a string not an object. Whereas you have used the incorrect type as an argument for your constructor.

public Message(object serializableObject); // should be a string

To correct your class, you need to design it the following way...

public class Message
{
    private readonly string _json;

    public Message(string json)
    {
        _json = json;            
    }

    public string GetBody() // not generic, but you get the idea now.
    {
        return json;
    }
}

Upvotes: 1

Related Questions