Search code examples
c#design-patternsdata-access-layermulti-tier

Pass "this" object by reference in C#


I need to pass the this object by reference in C#. But as you know this is not possible. I have a multi-tier application. In a nutshell, the DAL is getting Data from a web service in JSON Format. The JSON data has to be converted in Business-Layer Objects. Thus, I initialize the Business Layer object and pass it to the DAL. The DAL will convert the data to the object. I show an example of the code. First the DAL:

public Stream  GetSession ( ref BusinessLayer.Session session)
{
    Stream dataStream;
    // Use the ServiceManager to build send the data to the services
    // SOAServiceManager sm = new SOAServiceManager("http://www.Test.da/authentication.json","",DataAccessLayer.HTTPMethod.POST);

    // Add the Values 
    sm.AddCriteriaValue ("name","demo");
    sm.AddCriteriaValue ("password","demo");

    // Now it's show time and the datastream is full
    dataStream = sm.CommitPost ();

    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BusinessLayer.Session));

    session = (BusinessLayer.Session)ser.ReadObject(dataStream);

    return dataStream;
}

Now the Business Layer is using this DAL class:

namespace BusinessLayer
{
    public class Session
    {
        public bool Success { get; set; }
        public string Name { get; set; } 

        public Session ()
        {
            DataAccessLayer.Session dal_Session = new DataAccessLayer.Session ();
            dal_Session.GetSession ( ref this);
        }
    }
}

So the problem is, that it is not possible to send "this" as reference. So the solution that I see, is to create a copy object and send it to the DAL and then assign its values to the this object. But that is not a clever solution. Is there a way to solve that in C#?


Solution

  • You should not be creating a new Session object. Instead replace DataContractJsonSerializer with Newtonsoft.Json (since the former does not expose such method) and use a method that reads the JSON data and populates an existing object:

    using (var reader = new Newtonsoft.Json.JsonTextReader(new StreamReader(dataStream)))
    {
        var serializer = new Newtonsoft.Json.JsonSerializer();
        serializer.Populate(reader, session);
    }
    

    Alternatively do not use the constructor but instead a static factory method:

    public class Session
    {
        private Session() { }
        public static Create()
        {
            DataAccessLayer.Session dal_Session = new DataAccessLayer.Session ();
            var session = new Session();
            dal_Session.GetSession (ref session);
            return session;
        }
    }