Home > Enterprise >  Have a dynamic parameter for a List in Function
Have a dynamic parameter for a List in Function

Time:04-16

I have a SOAP APi which needs an XML string created to send as the request. There are a number of different XML strings required.

eg. the Customer and Item strings are quite different and there is no WDSL ability on this old software.

I have a function to check which API enpoint is being called, then get the action, uRL and envelope (XML) from predefined functions.

private static (string URL, string action, string envelope) getTaskDetails(string task, 
List<Object> envelopeList)
        {
            string _action = "";
            string _URL = "";
            string _envelope = "";


            switch (task)
            {
                case "getCustomerDetails":
                    _action = minfosDetails.minfosCustomerAction;
                    _URL = minfosDetails.minfosCustomerURL;
                    _envelope = getCustomerDetails(envelopeList);
                    break;

                default:
                    
                    break;

            }

            return (_URL, _action, _envelope);
        }

The aobve is the (not working) code.

What I want is the List (which I know is wrong) to accept any LIST thrown at it.

eg. I can send the customerList to it, or the ItemList or the staffList etc. Then when i run the switch, it will take the List and throw it into the subfunction to get the envolope created.

EDIT: Question answered, my working code below: Using

getTaskDetails<T>(string task, List<T> envelopeList)

To call the next function I used:

_envelope = getCustomerDetails(envelopeList.Cast<ACustomer>());

CodePudding user response:

You can try using generics so the method is going to change like this

private static (string URL, string action, string envelope) getTaskDetails<T>(List<T> envelopeList)

then you can check for what T Type is being passed instead of using your parameter string task

CodePudding user response:

It is not possible to simply cast List<object> to List<ACustomer>. You can create a new list instead.

_envelope = getCustomerDetails(envelopeList.Cast<ACustomer>().ToList());

OR, you could change the signature of getCustomerDetails to accept IEnumerable instead of List:

public static string getCustomerDetails(IEnumerable<ACustomer> customerList)

And then the .ToList() part is not needed, and no new list is created:

_envelope = getCustomerDetails(envelopeList.Cast<ACustomer>());

To use Cast extension method you have to be using System.Linq;

  • Related