Creating not settable properties for API use
This is an easy way to do it, without using non default constructors and such:
[Serializable] [DataContract] public class MyClass { [DataMember] public int? MyProperty1 { get; internal set; } [DataMember] public int? MyProperty2 { get; internal set; } }
In previous articles, I have mentioned why you should always mark DataContract and DataMember attributes even though it is not explicitly required anymore.
For your assembly where you set the property to be able to access the set, in this assembly use the below attribute:
[assembly: InternalsVisibleTo("MyOtherAssembly, PublicKey=MyPublicKeyLongString")]Btb, the XmlSerializer will not work when the sets are internal. To serialize as XML use the DataContractSerializer which is faster and better:public static string SerializeToXml(object input) { MemoryStream ms = new MemoryStream(); new DataContractSerializer(input.GetType()).WriteObject(ms, input); return Encoding.UTF8.GetString(ms.ToArray()); }
Once in a stupid interview, they asked me this question out of context and I have never done this before. It is not fair when you work on something specific for years and a guy comes in the interview and you ask questions as if, everyone would know what you worked on for the past few years.
Comments
Post a Comment