Thursday, June 30, 2011

Xml Serialization of Readonly Collection Property

I have a class:

public class AccountManagement {

public AccountManagement ()
{
this.Accounts=new Collection< Account>;
}
public Collection< Account> Accounts {get; private set}

}

When use a XML Serializer to serialize this class, there comes out an exception:

Unable to generate a temporary class (result=1). error CS0200: Property or indexer '' cannot be assigned to -- it is read only.

By Microsoft explanation, even we use private set, the Collection property is still writable inside the class, in order to do xml serialization, we need to write the class like:


public class AccountManagement {

private readonly Collection < Account> accounts;

public AccountManagement ()
{
this.accounts=new Collection< Accout>;
}
public Collection< Account> Accounts
{

get {return accounts;}

}

}

No comments: