How to skip some optional arguments in a library function

I am working on a Winforms C # application and I am using Twilio's SMS capabilities. Twilio has a "ListSmsMessages" function that looks like this:

public virtual SmsMessageResult ListSmsMessages(
    string to, string from, DateTime? dateSent, int? pageNumber, int? count);

      

The documentation says that each one is optional. I can successfully call the function, either by filling in the fields client.ListSmsMessages();

or filling in all the fields client.ListSMSMessages("to","from", date, 1,10);

, but I cannot select the options I want. For example, only client.ListSMSMessages("to",date);

.

I did some research and found that C # 4.0 should do something like client.ListSMSMessages(to:"to",datesent: date);

this does not work, however.

I am wondering if it is possible, because I am using Twilio;

instead of writing my own class, if this affects how I should name the optional parameters? Or perhaps their documentation is incorrect, indicating that they are optional.

+3


source to share


3 answers


These are nullable parameters, not optional. If you want to skip some of them, pass null

as value.

client.ListSMSMessages("to", null, date, null, null);

      

More details:



If you need additional arguments, then create your own function above the one in lib (building on Robert's answer :)):

public SmsMessageResult MyListSmsMessages(
    string to = null, string from = null, DateTime? dateSent = null, int? pageNumber = null, int? count = null)
{
  return client.ListSMSMessages(to, from, date, pageNumber, count); 
}

      

+8


source


Building on Marseille, answer what it would look like if Twilio actually built a function to have what C # calls additional parameters:

public virtual SmsMessageResult ListSmsMessages(
    string to = null, string from = null, DateTime? dateSent = null, 
    int? pageNumber = null, int? count = null);

      



Note that each parameter is assigned a default value that is used when you choose not to pass anything.

+4


source


Twilio only has two overloads:

SmsMessageResult ListSmsMessages()
SmsMessageResult ListSmsMessages
    (string to, string from, DateTime? dateSent, int? pageNumber, int? count)

      

You can pass null

arguments that you don't need, or, if you want the best readability, create your own extension method:

SmsMessageResult ListSmsMessages
    (this TwilioRestClient @this,
     string to = null, string from = null, DateTime? dateSent = null,
     int? pageNumber = null, int? count = null)
{
    @this.ListSmsMessages(to, from, dateSent, pageNumber, count);
}

      

With this extension method, you can call Twilio the way you want:

client.ListSMSMessages(to: "to", dateSent: date);

      

By the way, you can also create a pull request for Twilio. These are on GitHub and they seem to accept them. https://github.com/twilio/twilio-csharp

+4


source







All Articles