Reputation: 4443
It seems that an extension method in C# cannot overwrite the original object. Why is that? Example:
using System;
namespace ExtensionTest
{
public class MyTest {
public string MyName { get; set; }
}
class Program
{
static void Main(string[] args)
{
var myTest = new MyTest() { MyName = "Arne" };
Console.WriteLine("My name is {0}", myTest.MyName);
// Will write "My name is Arne"
myTest.AlterMyTest();
Console.WriteLine("My name is {0}", myTest.MyName);
// Will write "My name is Bertil"
myTest.OverwriteMyTest();
Console.WriteLine("My name is {0}", myTest.MyName);
// Will write "My name is Bertil" (why?)
}
}
public static class ExtensionClass{
public static void AlterMyTest(this MyTest myTest)
{
myTest.MyName = "Bertil";
}
public static void OverwriteMyTest(this MyTest myTest)
{
myTest = new MyTest() { MyName = "Carl" };
}
}
}
Upvotes: 0
Views: 183
Reputation: 50712
Because as usual, reference of the class is copied while passing to the method, and you are assigning new object to the new reference.
For not-extension methods, you can pass reference by ref/out
keywords
public static void Func(out MyClass b)
{
b = new MyClass();
}
...
MyClass b;
Func(out b);
Assert.IsNotNull(b);
but C# compiler doesn't allow to use ref
with this
(the reason is in David Arno's comment). You are free to remove this
keyword, and call static method instead of extension.
Upvotes: 5