Search code examples
c#azurefluentazure-sdk-.net

In Azure API for VM, is there a way to define many existing data disks with one method?


I have a block of fluent C# code:

If I knew how many disks existed the syntax would be:

    var tempVM = await azure.VirtualMachines.Define(targetVMName)
        .WithRegion(vm.Region)
        .WithExistingResourceGroup(targetResourceGroupName)
        .WithNewPrimaryNetworkInterface(nicDefinitions[0])
        .WithSpecializedOSDisk(disks[0], disks[0].OSType.Value)
        .WithSize(vm.Size)
        .WithTags(tags)
        .WithExistingDataDisk(d[0]) <<<<<<<
        .WithExistingDataDisk(d[1]) <<<<<<<
        .WithExistingDataDisk(d[2]) <<<<<<<
        .WithExistingDataDisk(d[3]) <<<<<<<
        .CreateAsync();

I may have 0 or more datadisks to add. Is there a fluent syntax to support 0 or more disks ?


Solution

  • Assuming this is using extension method on an interface named IWithManagedCreate, you have this method:

    public static IWithManagedCreate WithExistingDataDisk(this IWithManagedCreate vm, IDisk disk)
    {
        // ...      
        return vm; 
    }
    

    You could simply add an extension method of your own with a params IDisk[] overload:

    public static IWithManagedCreate WithExistingDataDisks(this IWithManagedCreate vm, params IDisk[] disks)
    {
        foreach (var disk in disks)
        {
            vm = vm.WithExistingDataDisk(disk);
        }
        return vm; 
    }
    

    And call it like that:

        .WithTags(tags)
        .WithExistingDataDisks(d) // passing the array containing 0 or more disks
        .CreateAsync();
    

    So, to answer the question, no, fluent syntax is nothing special, just a chain of method calls. When you chain method calls (by letting each method return something that you can call more methods on), you can't make them conditional; you can make a method however do nothing as demonstrated above. When you call it with an empty array, nothing happens.