Why or how does the following code work:
var mail = new MailMessage
{
To = { "hello@abc.com" }
};
given that both MailMessage.To is a readonly property, and it is an assignment operator?
As far as I can tell, this syntax triggers the Add method on MailAddressCollection, but I can't find the documentation that explains this magic for MailAddressCollection, or if it relates to either the Collection<T> type that it derives or the interfaces it inherits.
To show that the above syntax is being treated differently, the following approaches give compile time errors, complaining that the To property is readonly:
// Attempt 1
var mail = new MailMessage
{
To = "hello@abc.com"
};
// Attempt 2
var mail = new MailMessage();
mail.To = { "hello@abc.com" }
// Attempt 3
var mail = new MailMessage
{
To = new MailAddressCollection()
};
I'm sure there are other examples of this type of initialisation, but MailMessage is the first time I have come across it.