How to pass additional arguments

I have one function that has two fixed arguments. But the following arguments are not fixed; there can be two, three, or four.

These are runtime arguments, so how can I define this function?

My code looks like this:

public ObservableCollection<ERCErrors> ErrorCollectionWithValue (string ErrorDode, int MulCopyNo, dynamic arguments comming it should be 2 or 3) { return null; } 
+6
source share
3 answers

1) params (C # link)

 public ObservableCollection<ERCErrors>ErrorCollectionWithValue (string ErrorDode, int MulCopyNo, params object[] args) { //... } 

2) Named and optional arguments (C # Programming Guide)

 public ObservableCollection<ERCErrors> ErrorCollectionWithValue (string ErrorDode, int MulCopyNo, object arg1 = null, int arg2 = int.MinValue) { //... } 

3) And maybe a simple overloading method still works better, separating the logic of the method from different methods? From this link you can also find another description of named and optional parameters.

+12
source

One approach is overloaded methods

 public ObservableCollection<ERCErrors> ErrorCollectionWithValue (string ErrorDode, int MulCopyNo, int param1) { //do some thing with param1 } public ObservableCollection<ERCErrors> ErrorCollectionWithValue (string ErrorDode, int MulCopyNo, int param1,int param2) { //do some thing with param1 and param3 } public ObservableCollection<ERCErrors> ErrorCollectionWithValue (string ErrorDode, int MulCopyNo, int param1, int param2, int param3)  {    //do some thing with param1, param2 and param3  } 

then they would all be valid

 var err = ErrorCollectionWithValue("text", 10, 1); var err = ErrorCollectionWithValue("text", 10, 1,2); var err = ErrorCollectionWithValue("text", 10, 1,2,3); 

Another approach is to use optional parameters. You only need one method, not 3 in the first approach.

 public ObservableCollection<ERCErrors> ErrorCollectionWithValue (string ErrorDode, int MulCopyNo, int param1 = 0, int param2 = 0, optional int param3 = 0) { } 

they are still valid

 var err = ErrorCollectionWithValue("text", 10, 1); //defaults param2 and param3 to 0 var err = ErrorCollectionWithValue("text", 10, 1,2); //defaults param3 to 0 var err = ErrorCollectionWithValue("text", 10, 1,2,3); 

To skip any of the optional parameters, you need to use named parameters and this , which is only supported in C # 4.0 and above

 var err = ErrorCollectionWithValue("text", param3: 5); //skipping param1 and param2 

In the other two approaches, you cannot skip the order of parameters.

+5
source

You can go with params if the number of arguments can vary:

 public ObservableCollection<ERCErrors> ErrorCollectionWithValue(string errorCode, int num, params object[] args) { foreach(object obj in args) { //process args. } } 
+2
source

Source: https://habr.com/ru/post/926181/


All Articles