Search code examples
c#ref

Pass reference-type by reference to indicate it will be modified


I found some code in our app that passes a List<T> by reference to indicate it is modified:

void DoSomething(ref List<MyType> theList)
{
    theList.Add(new MyType());
}

I think it is clear that the ref-keyword is obsolete in this case, as we could also add new elements to the list without the keyword. However it indicates that we modify the lists or at least its elements. I find this is particulary useful if you have many parameters and want to see which of them are modified and which are just passed as values to do the job.

The question if this is okay is surely opinion-based and would be invalid for SO, I rather ask if there´s another approach to achieve this or if I even should care about it.

EDIT: To clarify my question a bit. This question is not on if a list is modified, this was just an example. Alternatively I´d also use any other reference-type, not just a List<T>.


Solution

  • However it indicates that we're changing the list.

    No, it does not. It indicates the reference can be changed. Using a ref keyword as 'identifier' something can change is bad in my opinion since it opens doors you might not want.

    I would advice to look into aspect-oriented programming, were you can assign attributes to method parameters. From the new Roslyn compiler with its code analysis services you could even check if the code violates the principal given.