Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a function with optional parameters in C# [duplicate]

I want to write a class for creating Excel files from Datagridviews. I want to add a bottom line with Subtotals for selected columns and the number of those columns change from 1 to 3. I want my function work like this

exportToExcel(string title, DataGridView dgv, int colId1, int colId2, int colId3); //for with 3 sub total 

//Example:
exportToExcel("Some Title",mygridview, 3);  //for 1 sub total
exportToExcel("Another Titme", othergridview, 5,6,7); //for 3 sub totals

Do I have to create functions for different variations or is there a way to make 2nd and 3rd column numbers optional ?

like image 949
Mustafa Ozbalci Avatar asked Feb 02 '26 22:02

Mustafa Ozbalci


1 Answers

You can use default values for the optional paramenters, something like:

exportToExcel(string title, DataGridView dgv, int colId1, int colId2 = 0, int colId3 = 0);

With a method like that you'd be able to make a call with 1 to 3 columns.

Also another approach would be this - the good thing about using this one is that if one day your number of columns increases or decreases you won't have to change the signature:

exportToExcel(string title, DataGridView dgv, params int[] colIds);
like image 187
devcrp Avatar answered Feb 05 '26 12:02

devcrp