I have a set of XML schema files provided to me. I cannot changed the XML as these will be updated on occasion. I am using xsd.exe to convert the schema files to generated c
Here's the final solution we came up with that leverages when I learned from the original answer. This static class is used to get and set the appropriate properties.
public static class XmlPolymorphicArrayHelper
{
public static TResult GetItem(TResult[] items, TIDentifier[] itemIdentifiers, TIDentifier itemIdentifier)
{
if (itemIdentifiers == null)
{
return default(TResult);
}
var i = Array.IndexOf(itemIdentifiers, itemIdentifier);
return i < 0 ? default(TResult) : items[i];
}
public static void SetItem(ref TResult[] items, ref TIDentifier[] itemIdentifiers, TIDentifier itemIdentifier, TResult value)
{
if (itemIdentifiers == null)
{
itemIdentifiers = new[] { itemIdentifier };
items = new[] { value };
return;
}
var i = Array.IndexOf(itemIdentifiers, itemIdentifier);
if (i < 0)
{
var newItemIdentifiers = itemIdentifiers.ToList();
newItemIdentifiers.Add(itemIdentifier);
itemIdentifiers = newItemIdentifiers.ToArray();
var newItems = items.ToList();
newItems.Add(value);
items = newItems.ToArray();
}
else
{
items[i] = value;
}
}
}
And then call them from the partial class like this:
public partial class LocationType
{
[XmlIgnore]
public string Address
{
get
{
return (string)XmlPolymorphicArrayHelper.GetItem(Items, ItemsElementName, ItemsChoiceType.Address);
}
set
{
XmlPolymorphicArrayHelper.SetItem(ref this.itemsField, ref this.itemsElementNameField, ItemsChoiceType.Address, value);
}
}
}
This sets/creates the appropriate member on the Items array and I can use this for the multiple classes that implement this pattern.