Search code examples
c#.netcloneimmutabilitysystem.net.mail

Clone or make a MailMessage Immutable in .NET / C#


I'm writing a small library where I'm writing some interfaces that takes a MailMessage object and returns a class back to me with a single send method that abstracts away how that MailMessage will be sent. I have control over the class that will do the actual sending, but I don't have control over the implementing strategy classes. I'd like to prevent any implementing strategy classes from altering the MailMessage. How can I make the MailMessage (and the collections it contains) immutable or create a clone of it? I don't see a .Clone method on MailMessage itself like I do on other classes. Will I have to result to new'ing up a new MailMessage object and doing a property-by-property set on that new MailMessage?

Note, I'm mostly a Java guy and am helping a client with C# 2.0 code, so I'm slightly unfamiliar with C# / .NET idioms for things like this. Any help is appreciated.


Solution

  • I don't think there is a quick solution for this. The MailMessage is inheritly mutable and isn't designed to be cloned or serialized/deserialized. If you need to make sure nobody can change it, don't cache it, but define a class that holds a copy of the values of the message and make new MailMessage instances out of this instance.