Saturday, November 15, 2008

Serializable attribute and get\set properties

For passing a class from XML web service a class needs to be Serializable, So that it could be converted to XML format.

This could be achieved by adding attribute [Serializable] to the class.

One thing to remember here is that only the member variables that are public or that have standard get\set property will get Serialized. Probable reason is use of Reflection during runtime serialization.

e.g. A class is similar to follows:

namespace MarketInformation

{

    [Serializable]

    public class PriceInformation

    {

        private string m_Name;

        public string Name

        {

            get

            {

                return m_Name;

            }

            set

            {

                m_Name = value;

                return;

            }

        }

        float[] m_Price = new float[7];

        public void SetPriceInfo(int index, float val)

        {

            m_Price[index] = val;

        }

        public float GetPriceInfo(int index)

        {

            return m_Price[index];

        }

         

}

}

 

This class contains a SetPriceInfo and GetPriceInfo methods. The regular get\set property is not written for m_Price.

While returning the object from web method the XML generated will be as follows:

  <?xml version="1.0" encoding="utf-8" ?>

  <PriceInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">

    <Name>Price Information</Name>

  </PriceInfo>

 

Adding standard get\set properties for m_Price:

        public float[] Price

        {

            get

            {

                return m_Price;

            }

            set

            {

                m_Price = value;

            }

        }

 

Now the XML generated will be correct as follows:

<?xml version="1.0" encoding="utf-8" ?>

  <PriceInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">

  <Name>Price Information</Name>

  <Price>

 <float>0</float>

 <float>10.1</float>

 <float>20.2</float>

 <float>30.3</float>

 <float>40.4</float>

 <float>50.5</float>

 <float>60.6</float>

  </Price>

  </PriceInfo>

 

I thought that the “get” property would be required at web service for serialization. The “set” property would be required at client consuming the web service for de-serialization. Tracing the web service suggests the same. Control goes only inside “get”. So I tried removing the “set” property for both member variables. Strangely the XML generated now is blank! :O

<PriceInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"/>

 

Conclusion is you have to add get as well as set properties for all member variables you want get serialized. 

No comments: