Search code examples
c#arraysobject-initializerscollection-initializer

Can't dynamically set array initializer length


I am using C# to hook into the FedEx API and I'm a bit stumped on how to modify some existing code to meet my needs. The snippet included is part of their canned code where they sample how to work with 1 commodity. However, when my code runs I will have n commodities...and I'm unsure how to dynamically address this.

As an example, if I have 3 commodities, and I manually add 3 new Commodity() statements it will work fine. However this needs to be dynamic.

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[3] { 
  new Commodity(), 
  new Commodity(), 
  new Commodity() 
};

Here is the start of the method, where the first line is what I need help with. After that I think putting everything else in a loop based on array size should be fine.

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[1] { 
  new Commodity() 
};

request.RequestedShipment.CustomsClearanceDetail.Commodities[0].NumberOfPieces = "1";
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Description = "Books";
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].CountryOfManufacture = "US";
//
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight = new Weight();
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight.Value = 1.0M;
request.RequestedShipment.CustomsClearanceDetail.Commodities[0].Weight.Units = WeightUnits.LB;

If I simply do this, I get an error:

request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[3] { 
  new Commodity() 
};

"An array initializer of length 3 is expected"


Solution

  • First, you don't have to mention 1 or 3 at all; put [] and let system compute the required length for you:

    // Commodity[3] will be created
    request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[] { 
      new Commodity(), 
      new Commodity(), 
      new Commodity() 
    };
    

    Or

    // Commodity[1] will be created
    request.RequestedShipment.CustomsClearanceDetail.Commodities = new Commodity[] { 
      new Commodity()
    };
    

    If you want to create an array of size n, you can try Linq:

    using System.Linq;
    
    ...
    
    int n = 3;
    
    request.RequestedShipment.CustomsClearanceDetail.Commodities = Enumerable
      .Range(0, n) 
      .Select(index => new Commodity())
      .ToArray();
    

    Or even

    int n = 3;
    
    // 3 equivalent commodities
    request.RequestedShipment.CustomsClearanceDetail.Commodities = Enumerable
      .Range(0, n) 
      .Select(index => new Commodity() {
         NumberOfPieces = "1", 
         Description = "Books",
         CountryOfManufacture = "US",
         Weight = new Weight() {
           Value = 1.0M,
           Units = WeightUnits.LB
         }
       })
      .ToArray();