Why .NET MailAddress' class properties are readonly

119 Views Asked by At

I want to inherit from MailAddress class to make a COM visible class, but MailAddress does not have a parameterless constructor, and COM doesn't have a mechanism to pass arguments to a constructor.

https://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress%28v=vs.110%29.aspx

so, i have to create a class like this, thinking about in just create it and later modify its properties:

public class Recipient : MailAddress
{
    public Recipient()
        : base("")//this is the contructor that takes less parameters, but can also add the other contructor parameters here
    {

    }
}

but then i realize that i can't modify its properties, because they are all read-only

anyone knows why they are readonly? and the class Attachment is made alike.

1

There are 1 best solutions below

1
On BEST ANSWER

The MailAddress class uses the immutable pattern -- so once the instance is created, it can't be modified (there are some benefits to this pattern -- since among other things it can help a lot with threading, since there are no lock contention issues).

The collection it gets placed into on the Message type (the to, from, cc collections) can be modified though. So you can always remove an existing MailAddress instance from one of those, and then create a new MailAddress class that replaces it with modified values.

Hope this helps,