简体   繁体   中英

C# passing List parameter

If I am writing a method that accepts two list parameters like so:

public void ModifyYourListsHere(List<MyClass1> list1, List<MyClass2> list2)
{
    ...add and remove from the lists
}

Should I pass these as ref or out if I want the caller to understand that the lists will be modified? Or do I just need to document the method? Or should the user expect that they might be modified?

You definitely don't want to use out , since that implies you will be assigning the variable before leaving the method (the compiler will actually enforce this).

ref will allow you to reassign the passed in parameter (definitely confusing to a user). You almost certainly don't want to use this either.

The best approach is to first, choose a good method name that makes it obvious the contents of one or both lists will be modified. Then use /// comments so that users of the function can see a more detailed description in Intellisense.

In case you are interested, the MSDN documentation for ref and out

Use ref if the function may change which List the variable points to and the caller shall reference the new list.

Use out if the function returns a new List that the caller didnt have a reference to before the call. This should only be used if the function needs to return multiple values.

If the List always exists before the function call you should not use either ref nor out .

Always document well if you function modifies the objects it receives as parameters!

If you want the first list to be modified then you have to use the ref keyword and the caller will know that he must use the ref before the list otherwise the method will be underlined by a red line saying that there is an error.

Update

You can also use the ref keyword to pass reference types. Passing a reference type by reference enables the called method to modify the object to which the reference parameter refers. The storage location of the object is passed to the method as the value of the reference parameter. If you change the storage location of the parameter, you change the storage location of the underlying argument. Source: MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM