Click here to Skip to main content
15,905,229 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 methods, one for inserting data and another for updating. These 2 methods have all arguments in common except that `update` method has an extra argument:

C#
if ()
    insert_data(arg1, arg2, arg3, arg4);
else
    update_data(ID, arg1, arg2, arg3 arg4);


I don't want to repeat `arg1` to `arg4`, so I have defined an `ArrayList`:

C#
var dataArrayList = new ArrayList()
{
    arg1,
    arg2,
    arg3,
    arg4
}


Is there anyway that can unzip the elements of this `ArrayList` like `*` character in Python?

C#
if ()
    insert_data(*dataArrayList);
else
    update_data(ID, *dataArrayList);


What I have tried:

I have searched through web questions, but the as solutions I should change my method definitions. I do not want to change method definitions.
Posted
Updated 28-Oct-20 3:28am

Unfortunately there's no easy way to do this without diving into reflection. I would recommend either accessing the ArrayList directly to access each of the values, or a better alternative might be to just create an intermediary class holding all of the values?
C#
public class Data {
  public string Value1 { get; set; }
  public string Value2 { get; set; }
  public int Value3 { get; set; }
}

You can then pass an instance of that object into the methods and have access to all of the relevant fields:
C#
var data = new Data
{
  Value1 = ..,
  Value2 = ..
};

if (..)
  insert_data(data);
else
  update_data(ID, data);
 
Share this answer
 
v2
Comments
Ali Majed HA 29-Oct-20 0:43am    
Although I have to change method's definition, it seems to be the best way. Thanks.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900