SkyeBoniwell SkyeBoniwell - 1 year ago 68
C# Question

How to access variables changed in method

I have a method called processOrders that takes 3 arguments and it does not return anything. One of the arguments is named currentOrder.

I will need the value of currentOrder after it's been processed by processOrders.

How do I get that value of currentOrder after it's been changed by the processOrders method when that method does not return anything?


Here's the code:

var orderTitle = "";
var currentOrder = 0;
var totalOrders = orders.Count;

processOrders(currentOrder, totalOrders, orders);

if(currentOrder > 10) {
// stuff...

processOrders(int currentOrder, int totalOrders, IList<Orders> orders)

while (currentOrder < totalOrders)

if(orders[currentOrder] < 5)
orderTitle = orderTitle + orders[currentOrder];
currentOrder ++;
} else {
yield return
CreateNewOrderForm(currentOrder, orderTitle)



Answer Source

Without getting too technical... The standard way of passing primitives (like "int" or "decimal") is to pass them by value. That means you pass the value in to the function and a new "copy" of the variable is made inside the function. That copy is only manipulated inside of the function, and is destroyed when the function exits.

If you want to manipulate the variable within the function and keep those changes, you will want to pass by reference. Passing by reference means that you give the function a "pointer" to your variable, and if the function makes any changes to the value, it will change your copy of the variable, the one it has a reference to.

To accomplish this, you must declare the parameter as a reference parameter, and then also call the function with a reference. Like this:

public void processOrders(ref int currentOrder, int totalOrders, IList<Orders> orders)

public void main(int[] args)
    processOrders(ref currentOrder, totalOrders, orders);
    if(currentOrder > 10)
        //do something

Note that you don't have to explicitly pass your list of orders by reference because objects are, by default, passed by reference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download