Alternative to using ref in foreach?

Any type within C# is passed actually by value. When you pass an instance of a class to a method what is actually passed is not the instance itself but a reference to it which itself is passed by value. So effectivly you're passing instances of a class as reference - which is why you call them reference-types.

In your case you just modify an existing instance referenced by that reference-value in your method, no need to use the ref-keyword.

foreach(var m in myList)
{
    MyMethod(m);
}

MyMethod(MyClass instance)
{
    instance.MyProperty = ...
}

If you'd really pass the reference by reference you'd re-assign the obj on every iteration within your loop which isn't allowed within a foreach-block. This would be similar to the following:

foreach(var m in myList)
{
    m = new MyClass();
}

On the other side you could also use a classic for-loop. However you'd need a temporary variable to store the outcome of your method:

for(int i = 0; i < myList.Length; i++)
{
    var tmp = myList[i];
    MyMethod(ref tmp);
    myList[i] = tmp;
}

use a temp variable to bypass the message

foreach(MyClass obj in myList)
{
    MyClass objTemp = obj;
    bool success = Modify(ref objTemp);
    // do things depending on success
}

private MyMethod(ref MyClass instance)
{
    instance.MyProperty = ...
}

You state

Modify is not reassigning the reference

Therefore, there is no reason the Modify(ref MyClass) function needs to pass argument by ref.

You should be able to do the same "modifications", whatever that is (please clarify that) by passing the object reference by value, i.e. removing the ref keyword.

So, the fix here should be changing your Modify function signature from Modify(ref MyClass) to Modify(MyClass)

Tags:

C#

Foreach

Ref