Share via


how fill List argument in method , without create new List before method?

Question

Sunday, October 12, 2014 6:49 PM

hi

i want  fill List<string> argument in method , without create new List<string> before method

public void MyMethod( List<string> Parameters1, List<string> Parameters2)
{
    // my code
}
MyMethod(???,???);//MyMethod({"iraq","french","india"},{"+15598754","+15598798","+15598752"})

All replies (2)

Sunday, October 12, 2014 7:05 PM ✅Answered

If you want to be able to initialize the List inside the method, you will need to pass it by reference (or as "out"), so that the method is able to initialize the reference that was not initialized outside:

public void MyMethod(out List<string> parameters1)
{
    parameters1 = new List<string>();
    parameters1.Add(...);
}

...

List<string> something;
MyMethod(out something);

Note that even though we didn't have to create the list outside the method, we did have to declare it. There is no way around this.


Sunday, October 12, 2014 7:55 PM ✅Answered

Well, since your method accepts two List<string> parameters, you must create two to be able to call it. You could of course create the lists "on the fly":

MyMethod(new List<string>() { "iraq", "french", "india"}, new List<string>() {"+15598754","+15598798","+15598752"} );

Anyway, you must the create the list somewhere to be able to fill it.

Please remember to mark helpful posts as answer and/or helpful.