I'm only using Code Analysis for cleaning, organizing and ensuring these changes are globally performed for all instances of a particular warning. I'm down to the final, and it's CA2227.
CA2227 Collection properties should be read only Change '' to be
read-only by removing the property setter.
Note this is for mapping of EDI documents. These classes are to represent a whole or part of an EDI document.
public class PO1Loop
{
public SegmentTypes.PO1LoopSegmentTypes.PO1 PO1 { get; set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID1> PIDRepeat1 { get; set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID2> PIDRepeat2 { get; set; }
public SegmentTypes.PO1LoopSegmentTypes.PO4 PO4 { get; set; }
/* Max Use: 8 */
public Collection<SegmentTypes.PO1LoopSegmentTypes.ACK> ACKRepeat { get; set; }
}
You can see all of the Collection properties will give me this warning, and there are hundreds of them. When using the above class I instantiate it without any data. Then externally I add the data and set each individual variable through its public accessor. I do not instantiate this class with all the data prepared and passed using a constructor method (IMO for the size these can reach it can easily wreak havoc on the eyes). When complete and all properties are assigned the class as a whole is then used to generate that part of a document it represents.
My question is, for the usage described above, what would be a better approach for setting this up correctly? Do I keep the public accessors and suppress this warning entirely, or is there a entirely different solution that would work?
Here's what MSDN says about the error, and also how you can avoid it.
Here's my take on the issue.
Consider, the following class:
class BigDataClass
{
public List<string> Data { get; set; }
}
This class will throw that exact same issue. Why? Because Collections do not need a setter. Now, we can do anything with that object: assign Data to an arbitrary List<string>, add elements to Data, remove elements from Data, etc. If we remove the setter, we only lose the ability to directly assign to that property.
Consider the following code:
class BigDataClass
{
private List<string> data = new List<string>();
public List<string> Data { get { return data; } } // note, we removed the setter
}
var bigData = new BigDataClass();
bigData.Data.Add("Some String");
This code is perfectly valid and in fact the recommended way to do things. Why? Because the List<string> is a reference to a memory location, that contains the remainder of the data.
Now, the only thing you cannot now do with this, is directly set the Data property. I.e. the following is invalid:
var bigData = new BigDataClass();
bigData.Data = new List<string>();
This is not necessarily a bad thing. You'll notice that on many .NET types this model is used. It's the basics of immutability. You usually do not want direct access to the mutability of Collections, as this can cause some accidental behavior that has strange issues. This is why Microsoft recommends you omit setters.
Example:
var bigData = new BigDataClass();
bigData.Data.Add("Some String");
var l2 = new List<string>();
l2.Add("String 1");
l2.Add("String 2");
bigData.Data = l2;
Console.WriteLine(bigData.Data[0]);
We might be expecting Some String, but we'll get String 1. This also means that you cannot reliably attach events to the Collection in question, so you cannot reliably determine if new values are added or values are removed.
A writable collection property allows a user to replace the collection with a completely different collection.
Essentially, if you only ever need to run the constructor, or assignment, once, then omit the set modifier. You won't need it, direct assignment of collections is against best-practices.
Now, I'm not saying never use a setter on a Collection, sometimes you may need one, but in general you should not use them.
You can always use .AddRange, .Clone, etc. on the Collections, you only lose the ability of direct assignment.
Serialization
Lastly, what do we do if we wish to Serialize or Deserialize a class that contains our Collection without a set? Well, there is always more than one way to do it, the simplest (in my opinion) is to create a property that represents the serialized collection.
Take our BigDataClass for example. If we wished to Serialize, and then Deserialize this class with the following code, the Data property would have no elements.
JavaScriptSerializer jss = new JavaScriptSerializer();
BigDataClass bdc = new BigDataClass();
bdc.Data.Add("Test String");
string serd = jss.Serialize(bdc);
Console.WriteLine(serd);
BigDataClass bdc2 = jss.Deserialize<BigDataClass>(serd);
So, to fix this, we can simply modify our BigDataClass a bit to make it use a new string property for Serialization purposes.
public class BigDataClass
{
private List<string> data = new List<string>();
[ScriptIgnore]
public List<string> Data { get { return data; } } // note, we removed the setter
public string SerializedData { get { JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Serialize(data); } set { JavaScriptSerializer jss = new JavaScriptSerializer(); data = jss.Deserialize<List<string>>(value); } }
}
Another option is always the DataContractSerializer (which is really a better option, in general.) You can find information about it on this StackOverflow question.
With current VS2019 we can simply do this:
public List<string> Data { get; } = new List<string>();
This satisfies CA2227 and can be serialized/deserialized.
The deserialization works because List<> has an "Add" method, and the serializer knows how to handle a read-only collection property with an Add method (the property is read-only but not the elements) (I use Json.Net, other serializers may behave differently).
Edit:
As pointed out it should be "=" and not "=>" (compiler will prevent you using "=>"). If we used "public List Data => new List();" then it would create a new list every time the property was accessed which is not what we want either.
Edit:
Note that this will NOT work if the type of the property is an interface, such as IList
Edit:
I think the handling of interfaces is determined by the serializer used. The following works perfectly. I'm sure all common serializers know how to handle ICollection. And if you have some custom interface that does not implement ICollection then you should be able to configure the serializer to handle it, but in that case CA2227 probably won't be triggered making it irrelevant here. (As it is a read-only property you have to assign a concrete value within the class so it should always be serializing and de-serializing a non-null value)
public class CA2227TestClass
{
public IList Data { get; } = new List<string>();
}
[TestMethod]
public void CA2227_Serialization()
{
var test = new CA2227TestClass()
{
Data = { "One", "Two", "Three" }
};
var json = JsonConvert.SerializeObject(test);
Assert.AreEqual("{\"Data\":[\"One\",\"Two\",\"Three\"]}", json);
var jsonObject = JsonConvert.DeserializeObject(json, typeof(CA2227TestClass)) as CA2227TestClass;
Assert.IsNotNull(jsonObject);
Assert.AreEqual(3, jsonObject.Data.Count);
Assert.AreEqual("One", jsonObject.Data[0]);
Assert.AreEqual("Two", jsonObject.Data[1]);
Assert.AreEqual("Three", jsonObject.Data[2]);
Assert.AreEqual(typeof(List<string>), jsonObject.Data.GetType());
}
š” Alternative Solution š”
In my situation, making the property read-only was not viable because the whole list (as a reference) could change to a new list.
I was able to resolve this warning by changing the properties' setter scope to be internal.
public List<Batch> Batches
{
get { return _Batches; }
internal set { _Batches = value; OnPropertyChanged(nameof(Batches)); }
}
Note one could also use private set...
The hint's (achilleas heal) of this warning seems really pointed to libraries for the documentation says (Bolding mine):
An externally visible writable property is a type that implements
System.Collections.ICollection.
For me it was, "Ok, I won't make it viewable externally...." and internal was fine for the app.
Thanks to #Matthew, #CraigW and #EBrown for helping me understanding the solution for this warning.
public class PO1Loop
{
public SegmentTypes.PO1LoopSegmentTypes.PO1 PO1 { get; set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID1> PIDRepeat1 { get; private set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID2> PIDRepeat2 { get; private set; }
public SegmentTypes.PO1LoopSegmentTypes.PO4 PO4 { get; set; }
/* Max Use: 8 */
public Collection<SegmentTypes.PO1LoopSegmentTypes.ACK> ACKRepeat { get; private set; }
public PO1Loop()
{
PIDRepeat1 = new Collection<SegmentTypes.PO1LoopSegmentTypes.PID1>();
PIDRepeat2 = new Collection<SegmentTypes.PO1LoopSegmentTypes.PID2>();
ACKRepeat = new Collection<SegmentTypes.PO1LoopSegmentTypes.ACK>();
}
}
When wanting to assign data to the collection types use AddRange, Clear or any other variation of method for modifying a collection.
Only while binding DTO, you need to suppress warnings.
otherwise a custom ModelBinder is required custom ModelBinder to bind collections.
quoting the rule documentation:
When to suppress warnings
You can suppress the warning if the property is part of a Data Transfer Object (DTO) class.
Otherwise, do not suppress warnings from this rule.
https://learn.microsoft.com/pt-br/visualstudio/code-quality/ca2227?view=vs-2019
DTOs often require serialization and deserialization. Thus, they are required to be mutable.
Having to create an alternate backing property is a pain.
Simply change the property type from List<string> to IReadOnlyList<string> then this works as expected without CA2227.
The collection is set via the property but you can also cast to List<string> if you wish to append or delete items.
class Holder
{
public IReadOnlyList<string> Col { get; set; } = new List<string>();
}
var list = new List<string> { "One", "Two" };
var holder = new Holder() { Col = list } ;
var json = JsonConvert.SerializeObject(holder);
// output json {"Col":["One","Two"]}
var deserializedHolder = JsonConvert.DeserializeObject<Holder>(json);
I had to fix some of the CA2227 violations, so i had to add the "readonly" keyword to the collection field and then of course, had to remove the setter property. Some code that have used the setter, just created a new collection object which initially was empty. This code sure did not compile so i had to add a SetXxx() method in order to realize the missing setter's functionality. I did it like this:
public void SetXxx(List<string> list)
{
this.theList.Clear();
this.theList.AddRange(list);
}
The code of callers using the setter has been replaced with a call to the method SetXxx().
Instead of creating a complete new list, the existing list now will be cleared and filled with new items from another list, passed in as a parameter. The original list, due to the fact it is readonly and created only once, will always remain.
I believe this is also a good way to avoid that the garbagae collector has to delete old objects that got out of scope and second, to create new collection objects although there is already one.
As an addition to Der Kommissar's excellent answer.
Starting with .NET 5 (C# 9.0) there are init-only properties. These properties are only settable under specific circumstances, see here for reference.
The following example should not raise a warning CA2227, yet still allow for the collection being set during object initialization.
using System.Collections.Generic;
namespace BookStore
{
public class BookModel
{
public ICollection<string> Chapters { get; init; }
}
}
Note that the current version of the .NET SDK still raises a warning when using the built-in analyzer (not the NuGet package). This is a known bug and should be fixed in the future.
To cover all the possible scenarios to resolve CA2227 error:
This covers the Entity relationship mapping when we use Entity Framework.
class Program
{
static void Main(string[] args)
{
ParentClass obj = new ParentClass();
obj.ChildDetails.Clear();
obj.ChildDetails.AddRange();
obj.LstNames.Clear();
obj.LstNames.AddRange();
}
}
public class ChildClass
{ }
public class ParentClass
{
private readonly ICollection<ChildClass> _ChildClass;
public ParentClass()
{
_ChildClass = new HashSet<ChildClass>();
}
public virtual ICollection<ChildClass> ChildDetails => _ChildClass;
public IList<string> LstNames => new List<string>();
}
Related
I am getting started with c#. I am asked to do an assignement that contains writing a unit test for a setter and checking its output. I don't follow the meaning of testing something very trivial that does not contain any logic. here's the example (SetKeywords() is the method to be tested):
public struct Keyword
{
private string keyword;
private KeywordTypes type;
public Keyword(string keyword, KeywordTypes Type =
KeywordTypes.String)
{
this.keyword = keyword;
this.type = Type;
}
public string GetString()
{
return this.keyword;
}
public KeywordTypes WhichType()
{
return this.type;
}
}
public class ShopParser
{
private Keyword[] keywords = new Keyword[0];
public void **SetKeywords**(Keyword[] tags)
{
keywords = tags;
}
}
public Keyword[] GetKeywords()
{
return this.keywords;
}
public static KeywordPair[] ExtractFromTaG(ShopParser parser, string
serializedInput)
{
var findings = new KeywordPair[0];
foreach (var keyword in parser.GetKeywords())
{
var start = serializedInput.IndexOf(keyword.GetStart());
// Check if keyword is in input string, if not continue
with next keyword.
if (start <= -1) continue;
var end = serializedInput.LastIndexOf(keyword.GetEnd());
// Extract the thing between the tags. Tag excluded
start += keyword.GetStart().Length;
var substring = serializedInput.Substring(start, end -
start);
// Add substring to result list
var tmp = new KeywordPair[findings.Length + 1];
var i = 0;
for (; i < findings.Length; ++i)
{
tmp[i] = findings[i];
}
tmp[i] = new KeywordPair(keyword, substring);
findings = tmp;
}
return findings;
}
}
Lack of complex code does not mean there are no design decisions by the author of the class that should be verified and protected by unit tests. I.e. the fact you picked value type for items in the collection makes some behaviors impossible and some trivial - the test are there to clarify that class implements that design decision properly and protects the behavior of the class in case of future modifications.
Unit tests for setters for properties of a collection type (unlike value type int) are actually non trivial because one must verify that contract of the class is defined and properly supported - does setter make a copy of a collection or reference existing one, does it make deep or shallow copy? Testing each of the cases properly is definitely not a trivial task. (Same to lesser extent applies to all reference type properties, but in non-collection cases expectations of behavior are usually more aligned with default).
So what you want to do before writing the test is to decide the behavior of your collection property - does it make copy at the moment of setting or refers to the original live instance. If collection would be of reference type (not the case in the question) you also need to decide if it takes shallow or deep copy (deep copy is unusual).
After you made the decision it is somewhat trivial to write the test to verify. You add following tests:
is the collection exposed via getter has the same items in the same order as one used to call setter (applies to both copy and reference approaches)
use setter with a collection and modify original collection (in case of an array change items in the collection). Verify that the collection exposed by the getter behaves properly (either matches updated one for live reference or stays the same for copied one)
if using collection of non-immutable reference types verify that modifying individual items behave as expected (either reflects modification for non-deep copy or stays the same)
if collection just refers to original one tests may be shortened to just checking for reference equality between the original and value returned by the getter, but doing so will not document expected behavior and limit ability to modify in the future.
One may need additional test to validate that collection returned as result of the getter behaves as designed by the class author - in particular if modification of the resulting collection are reflected in the class' state or not (getter returning shallow/deep copy of the state or just exposing internal state directly as shown in the question).
Please note that it is discouraged to have setters for collection properties - see CA2227: Collection properties should be read only. So code in the question sort of follows the recommendation but better name like "AddKeywords"/"ReplaceKeywords" would clarify behavior rather than general "set".
How to test?
When you call SetKeywords, it should do something. Right now it sets the internal array keywords. So the question you need to ask yourself is how can you be sure it did that? Well you have a GetKeywords method which returns the internal array so we can use that to conduct our tests as below:
[TestClass]
public class ShopParserTests
{
[TestMethod]
public void SetKeyWords__WhenGivenAnArray__MustSetTheInternalArray()
{
// Arrange
var k1 = new Keyword("One", KeywordTypes.String);
var k2 = new Keyword("Two");
var parser = new ShopParser();
var keys = new Keyword[] { k1, k2 };
// Act
parser.SetKeywords(keys);
// Assert
Keyword[] keysReturned = parser.GetKeywords();
Assert.AreEqual(keysReturned[0].GetString(), k1.GetString());
Assert.AreEqual(keysReturned[0].WhichType(), k1.WhichType());
Assert.AreEqual(keysReturned[1].GetString(), k2.GetString());
Assert.AreEqual(keysReturned[1].WhichType(), k2.WhichType());
// More tests
}
}
Some Suggestions
Keep in mind that you may need to write a lot more tests based on your requirements. For example, what if the user does this:
Keyword[] keysReturned = parser.GetKeywords();
keys[0] = new Keyword();
Do you want to allow that?
Also, in C# your classes can be simplified and take advantage of properties. So your Keyword and ShopParser classes be written like this:
public struct Keyword
{
public Keyword(string keyword, KeywordTypes type =
KeywordTypes.String)
{
this.TheKeyword = keyword;
this.KeyType= type;
}
public string TheKeyword { get; private set; }
public KeywordTypes KeyType { get; private set; }
}
public class ShopParser
{
public void SetKeywords(Keyword[] tags)
{
this.KeyWords = tags;
}
public Keyword[] KeyWords { get; private set; }
}
Recently, I came across some code that looked like this:
public class Test
{
public ICollection<string> Things { get; set; }
public Test()
{
Things = new List<string> { "First" };
}
public static Test Factory()
{
return new Test
{
Things = { "Second" }
};
}
}
Calling Test.Factory() results in a Test object with a Things collection containing both "First" and "Second".
It looks like the line Things = { "Second" } calls the Add method of Things. If the ICollection is changed to an IEnumerable, there is a syntax error stating "IEnumerable<string> does not contain a definition for 'Add'".
It is also apparent that you can only use this kind of syntax in an object initialiser. Code such as this is invalid:
var test = new Test();
test.Things = { "Test" };
What is the name of this feature? In which version of C# was it introduced? Why is it only available in object initialisers?
It is called a collection initializer and it was added in the C# 3 language specifications (section 7.5.10.3 at introduction, section 7.6.10.3 in the current specs). To be specific, the code you use uses an embedded collection initializer.
Collection initializer actually just call the Add method, which is required according to the specs.
As Quantic commented, the specs say:
A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the field or property, the elements given in the initializer are added to the collection referenced by the field or property.
That explains your unexpected results quite good.
Why is it only available in object initialisers?
Because it doesn't make sense elsewhere. You could just call the Add method yourself instead of using initializers for something else than initializing.
As Patrick already mentioned the collection initializer sequentially calls Add on the list. This assumes your property has been initialized by a constructor accordingly:
public class MyClass
{
public List<MyType> TheList { get; private set; }
public MyClass()
{
this.TheList = new List<MyType>();
}
}
If there is no such constructor that initializes your list you'll get a NullReferenceException in the following statement:
test.Things = { "Test" };
However this is something different than the following:
var m = new MyClass { TheList = new List<MyType> { ... } };
in which case you'll access the properties setter. Having none (or only a private one as in my example) leads to a compiler-error.
Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods...
I have an entity called Entity1 with (say) 10 public properties. In
one place in my code I want to output serialized JSON with (say) 3 of
those fields, in a second place I need to output 7 fields and in a
third place I might need to output (say) all 10 fields. How do I do
this using Newtonsoft's JSON library?
I can't use [JsonIgnore] or [DataMember] as that will apply to all
cases, so I won't be able to create "custom views" of the data (my own
terminology :-).
I tried to achieve this using an interface:
public interface Entity1View1
{
string Property1;
string Property2;
string Property5;
}
had Entity1 implement Entity1View1 and I passed an
IList<Entity1View1> to the JSON serializer (the objects were
actually just Entity1 objects). Didn't work: the serializer output
all the 10 public properties of Entity1.
The only other way I could think of was to implement
Entity1Wrapper1, Entity1Wrapper2 etc. type of classes where each
object would hold a corresponding instance of Entity1 and in turn
expose only those public properties that correspond to the properties
I want to show in "View1", "View2" etc. Then I pass lists of these
wrapper objects to the serializer (should work, haven't tried it yet).
Is there a better way?
If it matters, here's my configuration:
.Net 4.5
MVC 5
Don't know it that's the best way... but that's one.
One good point is that it will work either with json serialization or xml serialization, for example (which you may don't mind at all).
You can use ShouldSerialize<yourpropertyName> to manage what is serialized or not. <yourpropertyName> must match exactly the name of the property you wanna manage.
For example
public class Entity {
//assuming you want the default behavior to be "serialize all properties"
public Entity() {
ShouldSerializeProperty1 = true;
ShouldSerializeProperty2 = true;
ShouldSerializeProperty3 = true;
}
public string Property1 {get;set;}
public bool ShouldSerializeProperty1 {get;set;}
public string Property2 {get;set;}
public bool ShouldSerializeProperty2 {get;set;}
public int Property3 {get;set;}
public bool ShouldSerializeProperty3 {get;set;}
}
Then you could do, before all your serialization (of course, this could / should be extension methods).
var list = myListOfEntity;
//serialization1
foreach (var element in list) {
element.ShouldSerializeProperty3 = false;
}
//or serialization2
foreach (var element in list) {
element.ShouldSerializeProperty2 = false;
element.ShouldSerializeProperty3 = false;
}
I just wanted to make sure that this was the final step in processing.
You can create anonymous objects to serialize based on circumstance:
var json1Source1 = new {
Property1 = entityView1.Property1,
Property3 = entityView1.Property3
};
var json1Source2 = new {
Property2 = entityView1.Property2,
Property3 = entityView1.Property3
};
You can create jsonSource1 (or 2, 3, 4 etc) as anonymous objects that capture just what you need and then serialize them. The serializer will not care that they are anonymous.
Update 1:
To conditionally serialize a property, add a method that returns boolean with the same name as the property and then prefix the method name with ShouldSerialize..
This means that the solution suggested by Raphaƫl Althaus doesn't work as it relies on properties, whereas the serializer's documentation mentions that it has to be a method. I have verified that only a method returning a bool works as expected.
Original:
I finally went with a mix of Wrapper classes and the methodology suggested by Raphaƫl Althaus (with modifications): use Wrappers where some amount of sophistication may be required and use Raphaƫl's suggestion when simplicity will do.
Here's how I am using wrappers (intentionally left out null checks):
public class Entity1View1
{
protected Entity1 wrapped;
public Entity1View1(Entity1 entity)
{
wrapped = entity;
}
public String Property1
{
get { return wrapped.Property1; }
}
public String Property2
{
get { return wrapped.Property2; }
}
public String Property3
{
get { return wrapped.Property3.ToUpper(); }
}
}
This allows me to modify properties as their values are returned (as done with Property3 above) and lets me leverage inheritance to create new ways of serialization. For example, I can flatten the structure/hierarchy:
public class Entity1View2 : Entity1View1
{
pulic Entity1View2(Entity1 entity) : base(entity) { }
public long? SubEntityID
{
get { return wrapped.SubEntity.ID; }
}
}
For simpler cases where complexity/transformation of this sort is not required, I can simply use the ShouldSerialize* methods.
Same entity classes, different serialization outputs.
I try to use Json.NET for consuming an OData (like) service. My data structures have collection properties.
However all those properties are wrapped in a property called 'results' by my service. Even the main query which returns with a collection of the entities are wrapped into a root property called results.
Although I am not an OData expert I think this is pretty much a standard because if I try to send an object graph for update, and omit this 'results' wrapper around say a int collection type property then I got an error message from the server "A collection was found without the 'results' property. In OData, each collection must be represented as a JSON object with a property 'results'"
So I understand the server error message, and I also know how to workaround this. Of course I can mimic this object graph in my C# object model, but after writing the 101st wrapper in my object model it tends to be boring, and I do not want to reinvent the wheel.
My question is there an out of the box solution how to deal with this result property, and make it transparent? If this is a 'standard' I suppose not I am the first who are facing this task.
Thanks in advance
you can just write one and use it everywhere
public class OData<T> where T : IEnumerable
{
public T results { get; set; }
}
public class X
{
public string Prop { get; set; }
public OData<List<int>> List { get; set; }
}
class Program
{
static void Main(string[] args)
{
var x = new X()
{
Prop = "test",
List = new OData<List<int>> {results = new List<int>() {1, 2, 3}}
};
Console.WriteLine(JsonConvert.SerializeObject(x));
}
}
We have some setup classes in our project, which are serialized / deserialized with XmlSerializer from some .config-Files. In some of those setup classes we have collections of sub-setups like this:
using System;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
namespace Datev.Framework.Shared.Actions.Setup
{
[Serializable]
[XmlSerializerAssembly]
[XmlRoot("setup")]
public class SetupXml
{
public SetupXml()
{
SubSetups = new Collection<SubSetupXml>();
}
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public Collection<SubSetupXml> SubSetups { get; private set; }
}
[Serializable]
public class SubSetupXml
{
[XmlElement("someValue")]
public string SomeValue { get; set; }
}
}
We are using the attribute [XmlSerializerAssembly] to have the best performance for reading and writing the setups.
And here is my problem: We are using Collection to avoid the CA-Warning "Don't use arrays". When we make the setter of SubSetups public, we get the CA-Warning CA2227 "Don't make the setter of a collection public". If we make the setter of the property SubSetups private (like in the code sample), we'll get an error in the generated serializer. The method "GenerateSerializer" (invoked in a tool of us) the code has a line like this:
if (o.SubSetups == null) o.SubSetups = new Collection<SubSetupXml>();
If we make the setter private, we'll get a CS0200 "Property SubSetups cannont be assigned" during building the serializer.
Does anyone know how to make a correct setup with a generated serializer without suppressing a CA-Warning?
It is hard to tell: a "correct" setup depends highly on the context.
Just a quick idea: what happens if you move the logic from "GenerateSerializer" to the property getter? Would it be acceptable?
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public Collection<SubSetupXml> SubSetups {
get {
// subSetups needs to be a backing (private) field... is this a problem?
if (this.subSetups == null) this.subSetups = new Collection<SubSetupXml>();
}
private set;
}
This way, in "GenerateSerializer" you just get the collection. If the collection has not already been created, it will be inside the getter, without needing to create it outside the class.
Just an idea, let me know if it is not applicable.
If the situation is as straightforward as it seems then You don't need to check whether (o.SubSetups == null) because You have the line SubSetups = new Collection<SubSetupXml>(); in the SetupXml() constructor (that is, of course, if o is of type SetupXml). If you get rid of that if statement from the GenerateSerializer method and make the setter private You should be fine - there's no way the SubSetups property can be null unless there are some other ways of messing around with it that You didn't mention...
You could have something like this:
public class SetupXml
{
public SetupXml()
{
SubSetups = new Collection<SubSetupXml>();
}
[XmlIgnore]
public Collection<SubSetupXml> SubSetups { get; private set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[GeneratedCodeAttribute("Whatever", "1.0.0.0")]
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public SubSetupXml[] SerializationSubSetups
{
get
{
return SubSetups.ToArray();
}
get
{
SubSetups = new SubSetups();
if (value != null)
{
foreach(SubSetupXml ssx in value)
{
SubSetups.Add(ssx);
}
}
}
}
}
It's not perfect, but the EditorBrowsable attribute will prevent developers using this library (from another assembly) to see it displayed by intellisense/autocompletion tools. And the GeneratedCode attribute will prevent CA warning on it.
I assume that you have already consulted this article?
http://msdn.microsoft.com/en-us/library/ms182327.aspx
This strikes me as an important note in that article:
"Both binary and XML serialization support read-only properties that are collections. The System.Xml.Serialization.XmlSerializer class has specific requirements for types that implement ICollection and System.Collections.IEnumerable in order to be serializable."
Further to that you may be able to make more progress with the .Clear() and then .AddRange() approach, detailed there.
You can try to implement IXmlSerializable interface. It requires a bit more work but it gives you fine control on the serialization, and in your case access to the private class variables. In ReadXml method you just have to create and instance of your collection, iterate over each node in the source xml and parse the value
Changing the type of SubSetups to IEnumerable will get rid of the code analysis warning, but I can't tell if this is appropriate for you.
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public IEnumerable<SubSetupXml> SubSetups { get; set; }