Well, when you try to change the property of an instance of a class, you donβt even need to ref , because you are modifying the instance, not referring to it.
In this example, you do not need the ref keyword when changing the property:
class MyClass { public int MyProperty { get; set; } } static void Method(MyClass instance) { instance.MyProperty = 10; } static void Main(string[] args) { MyClass instance = new MyClass(); Method(instance); Console.WriteLine(instance.MyProperty); }
Output: 10
And here you need the ref keyword, because you are working with a link, not an instance:
... static void Method(MyClass instance) {
Output: 0
The same for your scenario, the extension methods are the same as regular static methods, and if you create a new object inside the method, you either use the ref keyword (this is not possible for extension methods) or return this object, otherwise the link will be lost.
So, in the second case, you should use:
public static List<T> Method<T>(this List<T> list, Func<T, bool> predicate) { return list.Where(predicate).ToList(); } List<int> ints = new List<int>(new int[] { 1, 2, 3, 4, 5 }); ints = ints.Method(i => i > 2); foreach(int item in ints) Console.Write(item + " ");
Output: 3, 4, 5
Fabjan
source share