2
class Program
{
    static void Main(string[] args)
    {
        var ball = new Ball();
        ball.MyApple.Name = "ramro apple";

        XmlSerializer ser = new XmlSerializer(typeof(Ball));
        var sb = new StringBuilder();
        var writer = new StringWriter(sb);

        ser.Serialize(writer, ball);

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sb.ToString());

        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
        object meroBall = ser.Deserialize(reader);
        Ball myBall = (Ball)meroBall;
    }
}

public class Apple
{
    public string Name
    {
        get;
        set;
    }
}

public class Ball
{
    public Ball()
    {
        _apple = new Apple();
    }

    public Apple MyApple
    {
        get { return _apple; }
    }

    private Apple _apple;
}

Here i have define private field Apple _apple in class Ball. It give me null value for MyApple. However, if i set Apple _apple as public field it will give the value as "ramro apple". Is there any way to get that value with using private field ? I try t

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
user1370468
  • 47
  • 2
  • 3
  • 8
  • 1
    I don't think this question is finished `I try t....` – m.edmondson May 02 '12 at 16:01
  • 1
    This behaviour is by design isn't it? You are effectively trying to serialize a readonly field. See http://stackoverflow.com/questions/5585364/force-xml-serialization-to-serialize-readonly-property for a similar question. – dash May 02 '12 at 16:01
  • @m.edmondson Perhaps an accidental interaction with an Apple and a Ball cut the OP off early ;-) – dash May 02 '12 at 16:02
  • possible duplicate of [Serializing private member data](http://stackoverflow.com/questions/802711/serializing-private-member-data) – Jeff Mercado May 02 '12 at 16:09

1 Answers1

1

This is because the XmlSerializer only works on members with both a public get and set... If you provide a public setter for MyApple it will work:

public class Ball
{
    public Ball()
    {
        _apple = new Apple();
    }

    public Apple MyApple
    {
        get { return _apple; }
        set { _apple = value; }
    }

    private Apple _apple;
}

This of course also assumes that both classes, Ball and Apple, have a public constructor that takes no arguments.

csharptest.net
  • 62,602
  • 11
  • 71
  • 89