-1

We are running a program in a loop on an enterprise scheduler throughout the day. The scheduler needs an integer return value, so we have to write the program to naturally return this. However, we want to keep a running tally of some information so I need to somehow pass in a collection object, retain it's values, add the new counts to the object, and then pass the new totals back to the program that called it.

I'm relatively new to using the out keyword so I might not even be going down the right path. Right now I am being told I need to assign control of the collection object before I can use it, however this will blow away any of the counts that it contains when it's passed in. Is there a way to use out to keep the values or should I use another method?

NealR
  • 10,189
  • 61
  • 159
  • 299
  • Out params don't use values passed in, if you want to pass a value in/out then use the 'ref' keyword. – Faraday Sep 10 '13 at 17:19
  • The question lacks details: what kind of data, is there a per-iteration aspect, any threading? A small bit of code would have cleared a lot of that up. – H H Sep 10 '13 at 17:22
  • Any reason for the downvote? The above comment was posted almost 24 hours ago and the solution below solves this problem perfectly. – NealR Sep 11 '13 at 18:45

2 Answers2

4

An out parameter doesn't logically have any value when it's passed in. Indeed, you can use a variable which isn't even definitely assigned:

int x; // No logical value yet
Foo(out x);

It sounds like you might want ref instead - although personally I try to avoid using ref or out, preferring to return all the results of my method using the return value where possible.

See my article on parameter passing for more about ref and out in general though.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

collection objects, like List<T> are reference types, so you don't even need to use the out keyword if you want your method to be able to change the content of the List<T> that you pass in

  • Perfect, I don't even need to use `out` or `ref`, just tested and that works. Thank you! – NealR Sep 10 '13 at 17:51
  • Even though this resolves your problem, I still strongly recommend reading [Jon Skeet's article](http://pobox.com/~skeet/csharp/parameters.html). Parameter passing is a fundamental C# concept; not having a full understanding of it will cause problems. – Brian Sep 10 '13 at 21:02