0

I have a datacontract on an inherited, partial class like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Domain
{
  [DataContract]
  public partial class IdCard : DomainObject<System.Int64>
  {
    private Group _grp;

    [DataMember]
    public virtual Group Grp
    {
        get { return _grp; }
        set { _grp = value; }
    }

    private bool _unproxized = true;
    public override object UnProxy()
    {
        if (this._unproxized)  // this prevents stackoverflow with cyclical references
        {
            this.Grp = (Group)this.Grp.UnProxy();
            this._unproxized = false;
        }

        return this;
    }
  }
}

For some reason, the _unproxized is never set to true; Any ideas why?

I know I can simply switch the logic around, but I'm curious why the member variable is not being initialized.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Lucas B
  • 11,793
  • 5
  • 37
  • 50
  • Sorry to ask, but how did you come to the conclusion that it isn't being initialized? – Brian Rasmussen Jan 18 '11 at 19:18
  • First, I know that a boolean defaults to false. Second, the code inside the conditional is never getting called. Third, when I inspect it with a debugger during the conditional it is false. – Lucas B Jan 18 '11 at 20:09
  • "private initialized variable not initializing". The title of the question is a paradox. –  Jan 20 '11 at 05:48

4 Answers4

4

Has the instance that you are looking at been deserialized? During standard DataContract de-serialization no constructors are called and only DataMembers are assigned. The variable that you are looking at is not marked as a DataMember.

This thread describes the implementation of the behavior that you are seeing using an almost identical example.

Community
  • 1
  • 1
ErnieL
  • 5,773
  • 1
  • 23
  • 27
2

It's because when deserialising, the DataContract serialiser uses a type of reflection to create completely uninitialised object instances, to which it then applies data. That's why the DataContract serialiser doesn't require a parameterless constructor. (Even if you add one, it won't get called). If you mark the _unproxied field with a [DataMember] attribute, it will be true.

Boeckm
  • 3,264
  • 4
  • 36
  • 41
Dan
  • 21
  • 1
  • Nice explanation and it sounds rational, do you have any references to support that? It sounds like a bug to me that should be reported to MS bug tracker (connect.microsoft.com) – Lucas B Nov 07 '12 at 17:48
0

My suspicion is you are using web/service references. In this case the code (private variable) never gets to the client.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
0

try to assign varibles in a constructor like this:

public IdCard()
{
    _unproxized = true;
}
  • Agreed, that is a solution. I'm not asking for a solution though, I'm asking why it is not being initialized. – Lucas B Jan 18 '11 at 20:07