Search code examples
c#serializationbinaryformatter

Passed C# object to a function and tried to initialize values using deSerializer. The changes are not reflected outside the function


 public Reporter(String filePath, FileType type)
            {
                PropRnW = new PropertyFileReader(filePath, type, this);
            }   


public PropertyFileReader(String filePath, FileType type, Reporter reporter)
            {
                OriginalPath = filePath;
                Type = type;
                this.Read(reporter);
            } 

private void Read(Reporter m_reporter)
    {
        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream(SavePath, FileMode.Open, FileAccess.Read);

        m_reporter = (Reporter)formatter.Deserialize(stream);
        stream.Close();
    }

I checked the value of m_reporter in the function and the values are reflected accurately. Though when i check the values once outside the function they are not changed.


Solution

  • The problem with my code was that I was trying to assign a new instance to Reporter object in Read method:

    m_reporter = (Reporter)formatter.Deserialize(stream);
    

    i.e. Deserialize returns a new instance of an object. This new instance is assigned in Read method and thus is available in the scope of Read method. It treats m_reporter as a local variable. Thus as soon as we get out of scope of Read method, reporter has its original state.

    Thus, creating a property (as suggested by @Gaurav) in PropertyFileReader class and using it makes this new instance available even outside the Read method. Then we have to individually assign all the properties of property to the original instance. So, i modified the code as below:

        public Reporter(String filePath, FileType type)
                    {
                        PropRnW = new PropertyFileReader(filePath, type);
                        this.Property1 = PropRnW.m_reporter.Property1;
                        this.Property2 = PropRnW.m_reporter.Property2;
                    }   
    
        class PropertyFileReader
    {
        public Reporter m_reporter {get; set;}
    
        public PropertyFileReader(String filePath, FileType type)
                    {
                        OriginalPath = filePath;
                        Type = type;
                        this.Read();
                    } 
    
        private void Read()
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream(SavePath, FileMode.Open, FileAccess.Read);
    
                m_reporter = (Reporter)formatter.Deserialize(stream);
                stream.Close();
            }
    };