views:

146

answers:

1

Hi, I am debugging a code and one strange thing occurs. There is a string property say MyProperty. When I add breakpoint at the setter of the property and at the default constructor ( The only constructor ) the setter is called first. I dont know what is going on at other level of the code but this seems strange to me in any case. All the members are non static. The class has a [DataContract] attribute and members are [DataMember]. Can anybody explain this?

I cannot share any more code than this. Also the code is in a Silverlight project.

+5  A: 

Is this during WCF deserialization? In WCF deserialization, the constructor isn't called at all. That's by design. WCF objects are designed to be data transport objects, and any logic that resides behind setters and getters is dangerous at best. Chances are, you're seeing this behavior and concerned about it because you have something going on in business logic that resides in the setter. To work around this, I'd suggest decorating only automatic properties and fields with the [DataMember] attribute, which will prevent any other logic from being triggered. Also, be careful of any logic that would be performed in the constructor, that logic won't be executed during deserialization.

David Morton
Wow! that is surprising, have you got any references for that. I can't imagine how a serialisation scheme would not call a constructor yet assign property values via their mutator methods.
AnthonyWJones
Yes it is having WCF serialization I guess because we are using WCF services.
Tanmoy
I am adding validation logic at the setter like the following bloghttp://msmvps.com/blogs/theproblemsolver/archive/2008/12/30/data-validation-silverlight-versus-wpf-part-2.aspxand getting _errors null exception inside setters because of this reason. How can I work around this?
Tanmoy
@Anthony - it's true. Check out the OnDeserialized attribute for data classes, and this SO answer: http://stackoverflow.com/questions/178645/how-does-wcf-deserialization-instantiate-objects-without-calling-a-constructor/179486#179486
slugster
I think you mean to say WCF DEserialization.
P Daddy
@Tanmoy - I mentioned how to workaround it in my post. Don't decorate any property that has any business logic at all. The only members that should be decorated with [DataMember] should be class-level fields and automatic properties. Your validation should occur when you initially set the values from outside serialization and deserialization, it shouldn't happen during deserialization at all.
David Morton
@slugster: Thanks for that. That's a gotcha I was previously unaware of.
AnthonyWJones