This ties in a lot to questions like How to add a range of items to an IList?, where some of the answers might be useful. However, I'm interested in an actual usecase and how the maintainers intend for the SDK to be used in the right way.
I am trying to create a virtual network using the azure-sdk-for-net.
The sample works with hardcoded array expression initializers, but I have data arriving from some other source and need to construct VirtualNetworkData
from that incoming data.
As far as I have seen, this is an issue with all lists in the SDK.
This is what the sample does:
var data = new VirtualNetworkData
{
DhcpOptionsDnsServers = { "1", "2" }
}
From what I can decipher, this syntax somehow calls the Add
method on the IList
interface.
This approach won't work for me, as I have data that I need to build and manage on the fly.
This is not allowed, since DhcpOptionsDnsServers
only exposes a getter:
var myDnsServers = new List<string> { "1", "2" };
var data = new VirtualNetworkData
{
// CS0200: Property or indexer 'VirtualNetworkData.DhcpOptionsDnsServers' cannot be assigned to -- it is read only
DhcpOptionsDnsServers = myDnsServers
}
This error gave me the (probably bad) idea to extend the interface backing this property:
var myDnsServers = new List<string> { "1", "2" };
var data = new VirtualNetworkData
{
// CS1503: Argument 1: cannot convert from 'string[]' to 'string'
DhcpOptionsDnsServers = { myDnsServers.ToArray() }
};
With this extension, the above works but it feels like I violate all sorts of best practices.
internal static class CollectionExtension
{
public static void Add(this ICollection<string> list, string[] range)
{
range.ToList().ForEach(r => list.Add(r));
}
}
And lastly, one option is this:
var myDnsServers = new List<string> { "1", "2" };
var data = new VirtualNetworkData();
myDnsServers.ForEach(dns => data.DhcpOptionsDnsServers.Add(dns));
// Or concat
data.DhcpOptionsDnsServers.concat(myDnsServers);
I don't particularly like any of the options, but how I am supposed to work with the SDK and lists properly?