AAsk AAsk - 1 year ago 92
C# Question

Convert an array into an argument list


constructor requires 6 arguments:

DateTime date1 = new DateTime(2008, 1, 1, 6, 32, 0);

Now, I have

int[] dr = new int[]{2008, 1, 1, 6, 32, 0};

How can I "convert" that array into the argument list - something like
DateTime date1 = new DateTime(dr);

Answer Source

You cannot do it like that, because the constructor does not take an array; it takes six individual parameters. A straightforward approach of breaking array apart manually should work, though:

var date1 = new DateTime(dr[0], dr[1], dr[2], dr[3], dr[4], dr[5]);

If you have to do it in multiple spots in your code, make a helper method to hide this code:

static class DateHelper {
    public DateTime MakeFromComponents(int[] dr) {
        return new DateTime(dr[0], dr[1], dr[2], dr[3], dr[4], dr[5]);
var date1 = DateHelper.MakeFromComponents(dr);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download