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 { getinternal set; }
        
        [DataMember]
        public int? MyProperty2 { getinternal 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:

[assemblyInternalsVisibleTo("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

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory