As the error shows I don't have a setter for my property, but I don't want a setter, it should be readonly.
3 Answers
Edited: Make the setter internal
.
This will still be settable within the assembly, but it is a nice trick that works well when used on data objects located within an assembly that is consumed by others, as those consuming assemblies will not be able to set the property, but the various serializers can.

- 49,403
- 14
- 95
- 145
-
Protected won't allow the property to be set from outside the class, so deserialization will still fail... – Dan Puzey Mar 02 '10 at 12:17
-
@Dan - check my edit. I knew i had encountered this one before, but i had to go back and check how i dealt with it. You are right - i initially tried *protected* but found it didn't work, so used *internal* instead. – slugster Mar 02 '10 at 12:53
-
1Thanks guys!!! I choosed a different way: set{Throw new Exception("You can't set value for this property.")} Thanksss for your Inputs Dan and Slugster – BreakHead Mar 02 '10 at 13:21
-
@slugster - I'm still surprised that internal works, from a code point of view (because the serializer still shouldn't be able to see that member from outside of the assembly!), but it's good to know that it does! – Dan Puzey Mar 02 '10 at 13:21
-
@Qutbuddin: you should test your method, because I suspect you'll find that the data in that property (and possibly in that class) won't make it across the wire, because deserializing will throw your exception. – Dan Puzey Mar 02 '10 at 13:22
Remember that WCF needs to create an instance of the object from its serialized representation (often XML) and if the property has no setter it cannot assign a value. Objects are not transferred between the client and the server but only serialized representations, so the object needs to be reconstructed at each end.

- 1,023,142
- 271
- 3,287
- 2,928
Your question's a bit vague, but I guess this is the answer you're looking for:
Default Serialization will only work for read-write properties, because you can't rehydrate an object without setting property values. If you want it to work with the property being readonly, you need to implement the serialization interface yourself, rather than just adding attributes.
Assuming you're using DataContract serialization, I think the best option is to implement ISerializable and implement the methods yourself.

- 33,626
- 4
- 73
- 96