Alternative to using ref in foreach?

I have a modification method with a signature like

private bool Modify(ref MyClass obj); 

which will make changes to obj and indicate whether it will be returned. Modify does not reassign the link (I know this will not work), just changing the instance fields, so I want to use it to do the following:

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

I ran into a compilation problem because obj not passed with the ref keyword. However, if I put the ref keyword like this:

 bool success = Modify(ref obj); 

I get “I can’t use obj as ref / out because it is a“ foreach iteration variable. ”I understand that foreach uses an immutable iterator and why this does not work.

My question is, what is the easiest alternative to do something like this work?

I tried using

 foreach(int i = 0; i < myList.Count; i++) { bool success = Modify(ref myList[i]); // do things depending on success } 

but they I get: "a property or index cannot be passed as a parameter to ref".

Thanks for the help.

+7
source share
3 answers

You indicate

Edit does not reassign the link

Therefore, there is no reason why the Modify(ref MyClass) function should pass the ref argument.

You should be able to perform the same “modifications”, whatever it is (clarify this) by passing a reference to the object by value, i.e. removing the ref keyword.

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

+8
source

Any type in C # is passed by value. However, when you pass an instance of a class to a method, it is not the instance itself that is actually passed, but a reference to it, which itself is passed by value. So effectively, you pass instances of the class as links — that’s why you call them reference types.

This means that you are modifying the instance referenced by this reference value in your method, there is no need to use ref -keyword.

 foreach(var m in myList) { MyMethod(m); } MyMethod(MyClass instance) { instance.MyProperty = ... } 

If you really pass the link by reference, you will override obj at each iteration in your loop, which is not allowed in foreach -block.

Alternatively, you can also use the classic for loop. However, you will need a temporary variable to store the results of your method:

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

This is solved using LINQ.

My code is:

  private static List<string> _test = new List<string>(); public List<string> Test { get => _test; set => _test = value; } static void Main(string[] args) { string numString = "abcd"; _test.Add("ABcd"); _test.Add("bsgd"); string result = _test.Where(a => a.ToUpper().Equals(numString.ToUpper()) == true).FirstOrDefault(); Console.WriteLine(result + " linq"); } 
0
source

Source: https://habr.com/ru/post/1270340/


All Articles